blob: 470d2f686d28f36f624251b24be223555962d74c [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
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080056static constexpr int32_t POINTER_1_DOWN =
57 AMOTION_EVENT_ACTION_POINTER_DOWN | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
58static constexpr int32_t POINTER_1_UP =
59 AMOTION_EVENT_ACTION_POINTER_UP | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
60
Michael Wrightd02c5b62014-02-10 15:10:22 -080061// An arbitrary injector pid / uid pair that has permission to inject events.
62static const int32_t INJECTOR_PID = 999;
63static const int32_t INJECTOR_UID = 1001;
64
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000065// An arbitrary pid of the gesture monitor window
66static constexpr int32_t MONITOR_PID = 2001;
67
chaviwd1c23182019-12-20 18:44:56 -080068struct PointF {
69 float x;
70 float y;
71};
Michael Wrightd02c5b62014-02-10 15:10:22 -080072
Gang Wang342c9272020-01-13 13:15:04 -050073/**
74 * Return a DOWN key event with KEYCODE_A.
75 */
76static KeyEvent getTestKeyEvent() {
77 KeyEvent event;
78
Garfield Tanfbe732e2020-01-24 11:26:14 -080079 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
80 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
81 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050082 return event;
83}
84
Siarhei Vishniakouca205502021-07-16 21:31:58 +000085static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
86 ASSERT_EQ(expectedAction, receivedAction)
87 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
88 << MotionEvent::actionToString(receivedAction);
89}
90
Michael Wrightd02c5b62014-02-10 15:10:22 -080091// --- FakeInputDispatcherPolicy ---
92
93class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
94 InputDispatcherConfiguration mConfig;
95
Prabir Pradhanedd96402022-02-15 01:46:16 -080096 using AnrResult = std::pair<sp<IBinder>, int32_t /*pid*/>;
97
Michael Wrightd02c5b62014-02-10 15:10:22 -080098protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100099 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100
101public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000102 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +0800103
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800104 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700105 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
106 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
107 EXPECT_EQ(event.getDisplayId(), args.displayId);
108
109 const auto& keyEvent = static_cast<const KeyEvent&>(event);
110 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
111 EXPECT_EQ(keyEvent.getAction(), args.action);
112 });
Jackal Guof9696682018-10-05 12:23:23 +0800113 }
114
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700115 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
116 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
117 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
118 EXPECT_EQ(event.getDisplayId(), args.displayId);
119
120 const auto& motionEvent = static_cast<const MotionEvent&>(event);
121 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
122 EXPECT_EQ(motionEvent.getAction(), args.action);
123 EXPECT_EQ(motionEvent.getX(0), point.x);
124 EXPECT_EQ(motionEvent.getY(0), point.y);
125 EXPECT_EQ(motionEvent.getRawX(0), point.x);
126 EXPECT_EQ(motionEvent.getRawY(0), point.y);
127 });
Jackal Guof9696682018-10-05 12:23:23 +0800128 }
129
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700130 void assertFilterInputEventWasNotCalled() {
131 std::scoped_lock lock(mLock);
132 ASSERT_EQ(nullptr, mFilteredEvent);
133 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800134
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800135 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700136 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800137 ASSERT_TRUE(mConfigurationChangedTime)
138 << "Timed out waiting for configuration changed call";
139 ASSERT_EQ(*mConfigurationChangedTime, when);
140 mConfigurationChangedTime = std::nullopt;
141 }
142
143 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700144 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800145 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800146 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800147 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
148 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
149 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
150 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
151 mLastNotifySwitch = std::nullopt;
152 }
153
chaviwfd6d3512019-03-25 13:23:49 -0700154 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700155 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800156 ASSERT_EQ(touchedToken, mOnPointerDownToken);
157 mOnPointerDownToken.clear();
158 }
159
160 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700161 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800162 ASSERT_TRUE(mOnPointerDownToken == nullptr)
163 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700164 }
165
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700166 // This function must be called soon after the expected ANR timer starts,
167 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500168 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700169 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500170 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800171 std::unique_lock lock(mLock);
172 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500173 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800174 ASSERT_NO_FATAL_FAILURE(
175 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500176 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700177 }
178
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000179 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800180 const sp<WindowInfoHandle>& window) {
181 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
182 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
183 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500184 }
185
Prabir Pradhanedd96402022-02-15 01:46:16 -0800186 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
187 const sp<IBinder>& expectedToken,
188 int32_t expectedPid) {
189 std::unique_lock lock(mLock);
190 android::base::ScopedLockAssertion assumeLocked(mLock);
191 AnrResult result;
192 ASSERT_NO_FATAL_FAILURE(result =
193 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
194 const auto& [token, pid] = result;
195 ASSERT_EQ(expectedToken, token);
196 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500197 }
198
Prabir Pradhanedd96402022-02-15 01:46:16 -0800199 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000200 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500201 std::unique_lock lock(mLock);
202 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800203 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
204 const auto& [token, _] = result;
205 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000206 }
207
Prabir Pradhanedd96402022-02-15 01:46:16 -0800208 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
209 int32_t expectedPid) {
210 std::unique_lock lock(mLock);
211 android::base::ScopedLockAssertion assumeLocked(mLock);
212 AnrResult result;
213 ASSERT_NO_FATAL_FAILURE(
214 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
215 const auto& [token, pid] = result;
216 ASSERT_EQ(expectedToken, token);
217 ASSERT_EQ(expectedPid, pid);
218 }
219
220 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000221 sp<IBinder> getResponsiveWindowToken() {
222 std::unique_lock lock(mLock);
223 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800224 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
225 const auto& [token, _] = result;
226 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700227 }
228
229 void assertNotifyAnrWasNotCalled() {
230 std::scoped_lock lock(mLock);
231 ASSERT_TRUE(mAnrApplications.empty());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800232 ASSERT_TRUE(mAnrWindows.empty());
233 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500234 << "ANR was not called, but please also consume the 'connection is responsive' "
235 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700236 }
237
Garfield Tan1c7bc862020-01-28 13:24:04 -0800238 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
239 mConfig.keyRepeatTimeout = timeout;
240 mConfig.keyRepeatDelay = delay;
241 }
242
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000243 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800244 std::unique_lock lock(mLock);
245 base::ScopedLockAssertion assumeLocked(mLock);
246
247 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
248 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000249 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800250 enabled;
251 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000252 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
253 << ") to be called.";
254 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800255 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000256 auto request = *mPointerCaptureRequest;
257 mPointerCaptureRequest.reset();
258 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800259 }
260
261 void assertSetPointerCaptureNotCalled() {
262 std::unique_lock lock(mLock);
263 base::ScopedLockAssertion assumeLocked(mLock);
264
265 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000266 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800267 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000268 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800269 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000270 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800271 }
272
arthurhungf452d0b2021-01-06 00:19:52 +0800273 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
274 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800275 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800276 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800277 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800278 }
279
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800280 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
281 std::unique_lock lock(mLock);
282 base::ScopedLockAssertion assumeLocked(mLock);
283 std::optional<sp<IBinder>> receivedToken =
284 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
285 mNotifyInputChannelBroken);
286 ASSERT_TRUE(receivedToken.has_value());
287 ASSERT_EQ(token, *receivedToken);
288 }
289
Michael Wrightd02c5b62014-02-10 15:10:22 -0800290private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700291 std::mutex mLock;
292 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
293 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
294 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
295 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800296
Prabir Pradhan99987712020-11-10 18:43:05 -0800297 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000298
299 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800300
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700301 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700302 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800303 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
304 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700305 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800306 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
307 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700308
arthurhungf452d0b2021-01-06 00:19:52 +0800309 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800310 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800311
Prabir Pradhanedd96402022-02-15 01:46:16 -0800312 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
313 // for a specific container to become non-empty. When the container is non-empty, return the
314 // first entry from the container and erase it.
315 template <class T>
316 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
317 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
318 // If there is an ANR, Dispatcher won't be idle because there are still events
319 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
320 // before checking if ANR was called.
321 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
322 // to provide it some time to act. 100ms seems reasonable.
323 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
324 const std::chrono::time_point start = std::chrono::steady_clock::now();
325 std::optional<T> token =
326 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
327 if (!token.has_value()) {
328 ADD_FAILURE() << "Did not receive the ANR callback";
329 return {};
330 }
331
332 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
333 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
334 // the dispatcher started counting before this function was called
335 if (std::chrono::abs(timeout - waited) > 100ms) {
336 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
337 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
338 << "ms, but waited "
339 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
340 << "ms instead";
341 }
342 return *token;
343 }
344
345 template <class T>
346 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
347 std::queue<T>& storage,
348 std::unique_lock<std::mutex>& lock,
349 std::condition_variable& condition)
350 REQUIRES(mLock) {
351 condition.wait_for(lock, timeout,
352 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
353 if (storage.empty()) {
354 ADD_FAILURE() << "Did not receive the expected callback";
355 return std::nullopt;
356 }
357 T item = storage.front();
358 storage.pop();
359 return std::make_optional(item);
360 }
361
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600362 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700363 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800364 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800365 }
366
Prabir Pradhanedd96402022-02-15 01:46:16 -0800367 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
368 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700369 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800370 ASSERT_TRUE(pid.has_value());
371 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700372 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500373 }
374
Prabir Pradhanedd96402022-02-15 01:46:16 -0800375 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
376 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500377 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800378 ASSERT_TRUE(pid.has_value());
379 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500380 mNotifyAnr.notify_all();
381 }
382
383 void notifyNoFocusedWindowAnr(
384 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
385 std::scoped_lock lock(mLock);
386 mAnrApplications.push(applicationHandle);
387 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800388 }
389
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800390 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
391 std::scoped_lock lock(mLock);
392 mBrokenInputChannels.push(connectionToken);
393 mNotifyInputChannelBroken.notify_all();
394 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800395
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600396 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700397
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600398 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700399 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
400 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
401 const std::vector<float>& values) override {}
402
403 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
404 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000405
Chris Yefb552902021-02-03 17:18:37 -0800406 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
407
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600408 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409 *outConfig = mConfig;
410 }
411
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600412 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700413 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800414 switch (inputEvent->getType()) {
415 case AINPUT_EVENT_TYPE_KEY: {
416 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800417 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800418 break;
419 }
420
421 case AINPUT_EVENT_TYPE_MOTION: {
422 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800423 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800424 break;
425 }
426 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800427 return true;
428 }
429
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600430 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600432 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800433
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600434 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800435 return 0;
436 }
437
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600438 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800439 return false;
440 }
441
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600442 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
443 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700444 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800445 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
446 * essentially a passthrough for notifySwitch.
447 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800448 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800449 }
450
Sean Stoutb4e0a592021-02-23 07:34:53 -0800451 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800452
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800453 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
454 return pid == INJECTOR_PID && uid == INJECTOR_UID;
455 }
Jackal Guof9696682018-10-05 12:23:23 +0800456
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600457 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700458 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700459 mOnPointerDownToken = newToken;
460 }
461
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000462 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800463 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000464 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800465 mPointerCaptureChangedCondition.notify_all();
466 }
467
arthurhungf452d0b2021-01-06 00:19:52 +0800468 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
469 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800470 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800471 mDropTargetWindowToken = token;
472 }
473
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700474 void assertFilterInputEventWasCalledInternal(
475 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700476 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800477 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700478 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800479 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800480 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800481};
482
Michael Wrightd02c5b62014-02-10 15:10:22 -0800483// --- InputDispatcherTest ---
484
485class InputDispatcherTest : public testing::Test {
486protected:
487 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700488 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800489
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000490 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800491 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700492 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800493 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000494 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700495 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800496 }
497
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000498 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700499 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700501 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700503
504 /**
505 * Used for debugging when writing the test
506 */
507 void dumpDispatcherState() {
508 std::string dump;
509 mDispatcher->dump(dump);
510 std::stringstream ss(dump);
511 std::string to;
512
513 while (std::getline(ss, to, '\n')) {
514 ALOGE("%s", to.c_str());
515 }
516 }
Vishnu Nair958da932020-08-21 17:12:37 -0700517
chaviw3277faf2021-05-19 16:45:23 -0500518 void setFocusedWindow(const sp<WindowInfoHandle>& window,
519 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700520 FocusRequest request;
521 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000522 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700523 if (focusedWindow) {
524 request.focusedToken = focusedWindow->getToken();
525 }
526 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
527 request.displayId = window->getInfo()->displayId;
528 mDispatcher->setFocusedWindow(request);
529 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800530};
531
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
533 KeyEvent event;
534
535 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800536 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
537 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600538 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
539 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800540 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700541 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800542 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800543 << "Should reject key events with undefined action.";
544
545 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800546 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
547 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600548 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800549 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700550 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800551 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 << "Should reject key events with ACTION_MULTIPLE.";
553}
554
555TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
556 MotionEvent event;
557 PointerProperties pointerProperties[MAX_POINTERS + 1];
558 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800559 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800560 pointerProperties[i].clear();
561 pointerProperties[i].id = i;
562 pointerCoords[i].clear();
563 }
564
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800565 // Some constants commonly used below
566 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
567 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
568 constexpr int32_t metaState = AMETA_NONE;
569 constexpr MotionClassification classification = MotionClassification::NONE;
570
chaviw9eaa22c2020-07-01 16:21:27 -0700571 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800573 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700574 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
575 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700576 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
577 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700578 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800579 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700580 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800581 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800582 << "Should reject motion events with undefined action.";
583
584 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800585 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800586 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
587 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
588 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
589 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500590 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800591 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700592 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800593 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800594 << "Should reject motion events with pointer down index too large.";
595
Garfield Tanfbe732e2020-01-24 11:26:14 -0800596 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700597 AMOTION_EVENT_ACTION_POINTER_DOWN |
598 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700599 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
600 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700601 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500602 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800603 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700604 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800605 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606 << "Should reject motion events with pointer down index too small.";
607
608 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800609 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800610 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
611 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
612 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
613 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500614 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800615 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700616 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800617 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800618 << "Should reject motion events with pointer up index too large.";
619
Garfield Tanfbe732e2020-01-24 11:26:14 -0800620 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700621 AMOTION_EVENT_ACTION_POINTER_UP |
622 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700623 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
624 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700625 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500626 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800627 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700628 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800629 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800630 << "Should reject motion events with pointer up index too small.";
631
632 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800633 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
634 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700635 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700636 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
637 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700638 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800639 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700640 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800641 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800642 << "Should reject motion events with 0 pointers.";
643
Garfield Tanfbe732e2020-01-24 11:26:14 -0800644 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
645 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700646 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700647 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
648 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700649 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800650 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700651 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800652 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800653 << "Should reject motion events with more than MAX_POINTERS pointers.";
654
655 // Rejects motion events with invalid pointer ids.
656 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800657 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
658 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700659 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700660 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
661 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700662 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800663 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700664 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800665 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800666 << "Should reject motion events with pointer ids less than 0.";
667
668 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800669 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
670 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700671 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700672 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
673 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700674 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800675 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700676 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800677 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800678 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
679
680 // Rejects motion events with duplicate pointer ids.
681 pointerProperties[0].id = 1;
682 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800683 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
684 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700685 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700686 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
687 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700688 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800689 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700690 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800691 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800692 << "Should reject motion events with duplicate pointer ids.";
693}
694
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800695/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
696
697TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
698 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800699 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800700 mDispatcher->notifyConfigurationChanged(&args);
701 ASSERT_TRUE(mDispatcher->waitForIdle());
702
703 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
704}
705
706TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800707 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
708 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800709 mDispatcher->notifySwitch(&args);
710
711 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
712 args.policyFlags |= POLICY_FLAG_TRUSTED;
713 mFakePolicy->assertNotifySwitchWasCalled(args);
714}
715
Arthur Hungb92218b2018-08-14 12:00:21 +0800716// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700717static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700718// Default input dispatching timeout if there is no focused application or paused window
719// from which to determine an appropriate dispatching timeout.
720static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
721 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
722 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800723
724class FakeApplicationHandle : public InputApplicationHandle {
725public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700726 FakeApplicationHandle() {
727 mInfo.name = "Fake Application";
728 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500729 mInfo.dispatchingTimeoutMillis =
730 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700731 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800732 virtual ~FakeApplicationHandle() {}
733
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000734 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700735
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500736 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
737 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700738 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800739};
740
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800741class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800742public:
Garfield Tan15601662020-09-22 15:32:38 -0700743 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800744 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700745 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800746 }
747
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800748 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700749 InputEvent* event;
750 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
751 if (!consumeSeq) {
752 return nullptr;
753 }
754 finishEvent(*consumeSeq);
755 return event;
756 }
757
758 /**
759 * Receive an event without acknowledging it.
760 * Return the sequence number that could later be used to send finished signal.
761 */
762 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800763 uint32_t consumeSeq;
764 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800765
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800766 std::chrono::time_point start = std::chrono::steady_clock::now();
767 status_t status = WOULD_BLOCK;
768 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800769 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800770 &event);
771 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
772 if (elapsed > 100ms) {
773 break;
774 }
775 }
776
777 if (status == WOULD_BLOCK) {
778 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700779 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800780 }
781
782 if (status != OK) {
783 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700784 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800785 }
786 if (event == nullptr) {
787 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700788 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800789 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700790 if (outEvent != nullptr) {
791 *outEvent = event;
792 }
793 return consumeSeq;
794 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800795
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700796 /**
797 * To be used together with "receiveEvent" to complete the consumption of an event.
798 */
799 void finishEvent(uint32_t consumeSeq) {
800 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
801 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800802 }
803
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000804 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
805 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
806 ASSERT_EQ(OK, status);
807 }
808
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000809 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
810 std::optional<int32_t> expectedDisplayId,
811 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800812 InputEvent* event = consume();
813
814 ASSERT_NE(nullptr, event) << mName.c_str()
815 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800816 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700817 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800818 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800819
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000820 if (expectedDisplayId.has_value()) {
821 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
822 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800823
Tiger Huang8664f8c2018-10-11 19:14:35 +0800824 switch (expectedEventType) {
825 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800826 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
827 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000828 if (expectedFlags.has_value()) {
829 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
830 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800831 break;
832 }
833 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800834 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000835 assertMotionAction(expectedAction, motionEvent.getAction());
836
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000837 if (expectedFlags.has_value()) {
838 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
839 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800840 break;
841 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100842 case AINPUT_EVENT_TYPE_FOCUS: {
843 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
844 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800845 case AINPUT_EVENT_TYPE_CAPTURE: {
846 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
847 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000848 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
849 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
850 }
arthurhungb89ccb02020-12-30 16:19:01 +0800851 case AINPUT_EVENT_TYPE_DRAG: {
852 FAIL() << "Use 'consumeDragEvent' for DRAG events";
853 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800854 default: {
855 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
856 }
857 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800858 }
859
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100860 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
861 InputEvent* event = consume();
862 ASSERT_NE(nullptr, event) << mName.c_str()
863 << ": consumer should have returned non-NULL event.";
864 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
865 << "Got " << inputEventTypeToString(event->getType())
866 << " event instead of FOCUS event";
867
868 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
869 << mName.c_str() << ": event displayId should always be NONE.";
870
871 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
872 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100873 }
874
Prabir Pradhan99987712020-11-10 18:43:05 -0800875 void consumeCaptureEvent(bool hasCapture) {
876 const InputEvent* event = consume();
877 ASSERT_NE(nullptr, event) << mName.c_str()
878 << ": consumer should have returned non-NULL event.";
879 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
880 << "Got " << inputEventTypeToString(event->getType())
881 << " event instead of CAPTURE event";
882
883 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
884 << mName.c_str() << ": event displayId should always be NONE.";
885
886 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
887 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
888 }
889
arthurhungb89ccb02020-12-30 16:19:01 +0800890 void consumeDragEvent(bool isExiting, float x, float y) {
891 const InputEvent* event = consume();
892 ASSERT_NE(nullptr, event) << mName.c_str()
893 << ": consumer should have returned non-NULL event.";
894 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
895 << "Got " << inputEventTypeToString(event->getType())
896 << " event instead of DRAG event";
897
898 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
899 << mName.c_str() << ": event displayId should always be NONE.";
900
901 const auto& dragEvent = static_cast<const DragEvent&>(*event);
902 EXPECT_EQ(isExiting, dragEvent.isExiting());
903 EXPECT_EQ(x, dragEvent.getX());
904 EXPECT_EQ(y, dragEvent.getY());
905 }
906
Antonio Kantekf16f2832021-09-28 04:39:20 +0000907 void consumeTouchModeEvent(bool inTouchMode) {
908 const InputEvent* event = consume();
909 ASSERT_NE(nullptr, event) << mName.c_str()
910 << ": consumer should have returned non-NULL event.";
911 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
912 << "Got " << inputEventTypeToString(event->getType())
913 << " event instead of TOUCH_MODE event";
914
915 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
916 << mName.c_str() << ": event displayId should always be NONE.";
917 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
918 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
919 }
920
chaviwd1c23182019-12-20 18:44:56 -0800921 void assertNoEvents() {
922 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700923 if (event == nullptr) {
924 return;
925 }
926 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
927 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
928 ADD_FAILURE() << "Received key event "
929 << KeyEvent::actionToString(keyEvent.getAction());
930 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
931 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
932 ADD_FAILURE() << "Received motion event "
933 << MotionEvent::actionToString(motionEvent.getAction());
934 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
935 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
936 ADD_FAILURE() << "Received focus event, hasFocus = "
937 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800938 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
939 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
940 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
941 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000942 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
943 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
944 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
945 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700946 }
947 FAIL() << mName.c_str()
948 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800949 }
950
951 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
952
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800953 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
954
chaviwd1c23182019-12-20 18:44:56 -0800955protected:
956 std::unique_ptr<InputConsumer> mConsumer;
957 PreallocatedInputEventFactory mEventFactory;
958
959 std::string mName;
960};
961
chaviw3277faf2021-05-19 16:45:23 -0500962class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800963public:
964 static const int32_t WIDTH = 600;
965 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800966
Chris Yea209fde2020-07-22 13:54:51 -0700967 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700968 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500969 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800970 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500971 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700972 base::Result<std::unique_ptr<InputChannel>> channel =
973 dispatcher->createInputChannel(name);
974 token = (*channel)->getConnectionToken();
975 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800976 }
977
978 inputApplicationHandle->updateInfo();
979 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
980
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500981 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700982 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800983 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500984 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000985 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800986 mInfo.frameLeft = 0;
987 mInfo.frameTop = 0;
988 mInfo.frameRight = WIDTH;
989 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700990 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800991 mInfo.globalScaleFactor = 1.0;
992 mInfo.touchableRegion.clear();
993 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
chaviwd1c23182019-12-20 18:44:56 -0800994 mInfo.ownerPid = INJECTOR_PID;
995 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800996 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -0800997 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -0800998 }
999
Arthur Hungabbb9d82021-09-01 14:52:30 +00001000 sp<FakeWindowHandle> clone(
1001 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001002 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001003 sp<FakeWindowHandle> handle =
1004 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1005 displayId, mInfo.token);
1006 return handle;
1007 }
1008
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001009 void setTouchable(bool touchable) {
1010 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1011 }
chaviwd1c23182019-12-20 18:44:56 -08001012
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001013 void setFocusable(bool focusable) {
1014 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1015 }
1016
1017 void setVisible(bool visible) {
1018 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1019 }
Vishnu Nair958da932020-08-21 17:12:37 -07001020
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001021 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001022 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001023 }
1024
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001025 void setPaused(bool paused) {
1026 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1027 }
1028
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001029 void setPreventSplitting(bool preventSplitting) {
1030 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001031 }
1032
1033 void setSlippery(bool slippery) {
1034 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1035 }
1036
1037 void setWatchOutsideTouch(bool watchOutside) {
1038 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1039 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001040
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001041 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1042
1043 void setInterceptsStylus(bool interceptsStylus) {
1044 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1045 }
1046
1047 void setDropInput(bool dropInput) {
1048 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1049 }
1050
1051 void setDropInputIfObscured(bool dropInputIfObscured) {
1052 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1053 }
1054
1055 void setNoInputChannel(bool noInputChannel) {
1056 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1057 }
1058
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001059 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1060
chaviw3277faf2021-05-19 16:45:23 -05001061 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001062
Bernardo Rufino7393d172021-02-26 13:56:11 +00001063 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1064
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001065 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001066 mInfo.frameLeft = frame.left;
1067 mInfo.frameTop = frame.top;
1068 mInfo.frameRight = frame.right;
1069 mInfo.frameBottom = frame.bottom;
1070 mInfo.touchableRegion.clear();
1071 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001072
1073 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1074 ui::Transform translate;
1075 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1076 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001077 }
1078
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001079 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1080
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001081 void setIsWallpaper(bool isWallpaper) {
1082 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1083 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001084
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001085 void setDupTouchToWallpaper(bool hasWallpaper) {
1086 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1087 }
chaviwd1c23182019-12-20 18:44:56 -08001088
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001089 void setTrustedOverlay(bool trustedOverlay) {
1090 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1091 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001092
chaviw9eaa22c2020-07-01 16:21:27 -07001093 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1094 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1095 }
1096
1097 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001098
yunho.shinf4a80b82020-11-16 21:13:57 +09001099 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1100
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001101 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1102 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1103 expectedFlags);
1104 }
1105
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001106 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1107 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1108 }
1109
Svet Ganov5d3bc372020-01-26 23:11:07 -08001110 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001111 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001112 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1113 expectedFlags);
1114 }
1115
1116 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001117 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001118 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1119 expectedFlags);
1120 }
1121
1122 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001123 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001124 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1125 }
1126
1127 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1128 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001129 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1130 expectedFlags);
1131 }
1132
Svet Ganov5d3bc372020-01-26 23:11:07 -08001133 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001134 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1135 int32_t expectedFlags = 0) {
1136 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1137 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001138 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1139 }
1140
1141 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001142 int32_t expectedFlags = 0) {
1143 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1144 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001145 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1146 }
1147
1148 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001149 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001150 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1151 expectedFlags);
1152 }
1153
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001154 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1155 int32_t expectedFlags = 0) {
1156 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1157 expectedFlags);
1158 }
1159
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001160 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1161 int32_t expectedFlags = 0) {
1162 InputEvent* event = consume();
1163 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1164 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1165 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1166 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1167 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1168 }
1169
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001170 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1171 ASSERT_NE(mInputReceiver, nullptr)
1172 << "Cannot consume events from a window with no receiver";
1173 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1174 }
1175
Prabir Pradhan99987712020-11-10 18:43:05 -08001176 void consumeCaptureEvent(bool hasCapture) {
1177 ASSERT_NE(mInputReceiver, nullptr)
1178 << "Cannot consume events from a window with no receiver";
1179 mInputReceiver->consumeCaptureEvent(hasCapture);
1180 }
1181
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001182 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1183 std::optional<int32_t> expectedDisplayId,
1184 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001185 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1186 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1187 expectedFlags);
1188 }
1189
arthurhungb89ccb02020-12-30 16:19:01 +08001190 void consumeDragEvent(bool isExiting, float x, float y) {
1191 mInputReceiver->consumeDragEvent(isExiting, x, y);
1192 }
1193
Antonio Kantekf16f2832021-09-28 04:39:20 +00001194 void consumeTouchModeEvent(bool inTouchMode) {
1195 ASSERT_NE(mInputReceiver, nullptr)
1196 << "Cannot consume events from a window with no receiver";
1197 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1198 }
1199
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001200 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001201 if (mInputReceiver == nullptr) {
1202 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1203 return std::nullopt;
1204 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001205 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001206 }
1207
1208 void finishEvent(uint32_t sequenceNum) {
1209 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1210 mInputReceiver->finishEvent(sequenceNum);
1211 }
1212
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001213 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1214 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1215 mInputReceiver->sendTimeline(inputEventId, timeline);
1216 }
1217
chaviwaf87b3e2019-10-01 16:59:28 -07001218 InputEvent* consume() {
1219 if (mInputReceiver == nullptr) {
1220 return nullptr;
1221 }
1222 return mInputReceiver->consume();
1223 }
1224
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001225 MotionEvent* consumeMotion() {
1226 InputEvent* event = consume();
1227 if (event == nullptr) {
1228 ADD_FAILURE() << "Consume failed : no event";
1229 return nullptr;
1230 }
1231 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1232 ADD_FAILURE() << "Instead of motion event, got "
1233 << inputEventTypeToString(event->getType());
1234 return nullptr;
1235 }
1236 return static_cast<MotionEvent*>(event);
1237 }
1238
Arthur Hungb92218b2018-08-14 12:00:21 +08001239 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001240 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001241 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001242 return; // Can't receive events if the window does not have input channel
1243 }
1244 ASSERT_NE(nullptr, mInputReceiver)
1245 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001246 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001247 }
1248
chaviwaf87b3e2019-10-01 16:59:28 -07001249 sp<IBinder> getToken() { return mInfo.token; }
1250
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001251 const std::string& getName() { return mName; }
1252
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001253 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1254 mInfo.ownerPid = ownerPid;
1255 mInfo.ownerUid = ownerUid;
1256 }
1257
Prabir Pradhanedd96402022-02-15 01:46:16 -08001258 int32_t getPid() const { return mInfo.ownerPid; }
1259
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001260 void destroyReceiver() { mInputReceiver = nullptr; }
1261
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001262 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1263
chaviwd1c23182019-12-20 18:44:56 -08001264private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001265 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001266 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001267 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001268};
1269
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001270std::atomic<int32_t> FakeWindowHandle::sId{1};
1271
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001272static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001273 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001274 int32_t displayId = ADISPLAY_ID_NONE,
1275 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001276 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1277 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001278 KeyEvent event;
1279 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1280
1281 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001282 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001283 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1284 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001285
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001286 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1287 if (!allowKeyRepeat) {
1288 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1289 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001290 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001291 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001292 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001293}
1294
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001295static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001296 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001297 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1298}
1299
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001300// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1301// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1302// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001303static InputEventInjectionResult injectKeyDownNoRepeat(
1304 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001305 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1306 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1307 /* allowKeyRepeat */ false);
1308}
1309
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001310static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001311 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001312 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1313}
1314
Garfield Tandf26e862020-07-01 20:18:19 -07001315class PointerBuilder {
1316public:
1317 PointerBuilder(int32_t id, int32_t toolType) {
1318 mProperties.clear();
1319 mProperties.id = id;
1320 mProperties.toolType = toolType;
1321 mCoords.clear();
1322 }
1323
1324 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1325
1326 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1327
1328 PointerBuilder& axis(int32_t axis, float value) {
1329 mCoords.setAxisValue(axis, value);
1330 return *this;
1331 }
1332
1333 PointerProperties buildProperties() const { return mProperties; }
1334
1335 PointerCoords buildCoords() const { return mCoords; }
1336
1337private:
1338 PointerProperties mProperties;
1339 PointerCoords mCoords;
1340};
1341
1342class MotionEventBuilder {
1343public:
1344 MotionEventBuilder(int32_t action, int32_t source) {
1345 mAction = action;
1346 mSource = source;
1347 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1348 }
1349
1350 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1351 mEventTime = eventTime;
1352 return *this;
1353 }
1354
1355 MotionEventBuilder& displayId(int32_t displayId) {
1356 mDisplayId = displayId;
1357 return *this;
1358 }
1359
1360 MotionEventBuilder& actionButton(int32_t actionButton) {
1361 mActionButton = actionButton;
1362 return *this;
1363 }
1364
arthurhung6d4bed92021-03-17 11:59:33 +08001365 MotionEventBuilder& buttonState(int32_t buttonState) {
1366 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001367 return *this;
1368 }
1369
1370 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1371 mRawXCursorPosition = rawXCursorPosition;
1372 return *this;
1373 }
1374
1375 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1376 mRawYCursorPosition = rawYCursorPosition;
1377 return *this;
1378 }
1379
1380 MotionEventBuilder& pointer(PointerBuilder pointer) {
1381 mPointers.push_back(pointer);
1382 return *this;
1383 }
1384
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001385 MotionEventBuilder& addFlag(uint32_t flags) {
1386 mFlags |= flags;
1387 return *this;
1388 }
1389
Garfield Tandf26e862020-07-01 20:18:19 -07001390 MotionEvent build() {
1391 std::vector<PointerProperties> pointerProperties;
1392 std::vector<PointerCoords> pointerCoords;
1393 for (const PointerBuilder& pointer : mPointers) {
1394 pointerProperties.push_back(pointer.buildProperties());
1395 pointerCoords.push_back(pointer.buildCoords());
1396 }
1397
1398 // Set mouse cursor position for the most common cases to avoid boilerplate.
1399 if (mSource == AINPUT_SOURCE_MOUSE &&
1400 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1401 mPointers.size() == 1) {
1402 mRawXCursorPosition = pointerCoords[0].getX();
1403 mRawYCursorPosition = pointerCoords[0].getY();
1404 }
1405
1406 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001407 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001408 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001409 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001410 mButtonState, MotionClassification::NONE, identityTransform,
1411 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001412 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1413 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001414
1415 return event;
1416 }
1417
1418private:
1419 int32_t mAction;
1420 int32_t mSource;
1421 nsecs_t mEventTime;
1422 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1423 int32_t mActionButton{0};
1424 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001425 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001426 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1427 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1428
1429 std::vector<PointerBuilder> mPointers;
1430};
1431
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001432static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001433 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001434 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001435 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001436 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1437 injectionTimeout,
1438 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1439}
1440
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001441static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001442 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001443 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001444 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001445 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1446 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001447 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001448 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001449 MotionEvent event = MotionEventBuilder(action, source)
1450 .displayId(displayId)
1451 .eventTime(eventTime)
1452 .rawXCursorPosition(cursorPosition.x)
1453 .rawYCursorPosition(cursorPosition.y)
1454 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1455 .x(position.x)
1456 .y(position.y))
1457 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001458
1459 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001460 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001461}
1462
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001463static InputEventInjectionResult injectMotionDown(
1464 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1465 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001466 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001467}
1468
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001469static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001470 int32_t source, int32_t displayId,
1471 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001472 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001473}
1474
Jackal Guof9696682018-10-05 12:23:23 +08001475static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1476 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1477 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001478 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1479 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1480 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001481
1482 return args;
1483}
1484
chaviwd1c23182019-12-20 18:44:56 -08001485static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1486 const std::vector<PointF>& points) {
1487 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001488 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1489 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1490 }
1491
chaviwd1c23182019-12-20 18:44:56 -08001492 PointerProperties pointerProperties[pointerCount];
1493 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001494
chaviwd1c23182019-12-20 18:44:56 -08001495 for (size_t i = 0; i < pointerCount; i++) {
1496 pointerProperties[i].clear();
1497 pointerProperties[i].id = i;
1498 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001499
chaviwd1c23182019-12-20 18:44:56 -08001500 pointerCoords[i].clear();
1501 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1502 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1503 }
Jackal Guof9696682018-10-05 12:23:23 +08001504
1505 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1506 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001507 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001508 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1509 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001510 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1511 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001512 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1513 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001514
1515 return args;
1516}
1517
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001518static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1519 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1520}
1521
chaviwd1c23182019-12-20 18:44:56 -08001522static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1523 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1524}
1525
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001526static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1527 const PointerCaptureRequest& request) {
1528 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001529}
1530
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001531/**
1532 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1533 * broken channel.
1534 */
1535TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1536 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1537 sp<FakeWindowHandle> window =
1538 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1539 ADISPLAY_ID_DEFAULT);
1540
1541 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1542
1543 // Window closes its channel, but the window remains.
1544 window->destroyReceiver();
1545 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1546}
1547
Arthur Hungb92218b2018-08-14 12:00:21 +08001548TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001549 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001550 sp<FakeWindowHandle> window =
1551 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001552
Arthur Hung72d8dc32020-03-28 00:48:39 +00001553 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001554 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1555 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1556 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001557
1558 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001559 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001560}
1561
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001562TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1563 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1564 sp<FakeWindowHandle> window =
1565 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1566
1567 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1568 // Inject a MotionEvent to an unknown display.
1569 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1570 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1571 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1572
1573 // Window should receive motion event.
1574 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1575}
1576
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001577/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001578 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001579 * This test serves as a sanity check for the next test, where setInputWindows is
1580 * called twice.
1581 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001582TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001583 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001584 sp<FakeWindowHandle> window =
1585 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1586 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001587
1588 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001589 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001590 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1591 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001592 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001593
1594 // Window should receive motion event.
1595 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1596}
1597
1598/**
1599 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001600 */
1601TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001602 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001603 sp<FakeWindowHandle> window =
1604 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1605 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001606
1607 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1608 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001609 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001610 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1611 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001612 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001613
1614 // Window should receive motion event.
1615 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1616}
1617
Arthur Hungb92218b2018-08-14 12:00:21 +08001618// The foreground window should receive the first touch down event.
1619TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001620 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001621 sp<FakeWindowHandle> windowTop =
1622 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1623 sp<FakeWindowHandle> windowSecond =
1624 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001625
Arthur Hung72d8dc32020-03-28 00:48:39 +00001626 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001627 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1628 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1629 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001630
1631 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001632 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001633 windowSecond->assertNoEvents();
1634}
1635
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001636/**
1637 * Two windows: A top window, and a wallpaper behind the window.
1638 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1639 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001640 * 1. foregroundWindow <-- dup touch to wallpaper
1641 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001642 */
1643TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1644 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1645 sp<FakeWindowHandle> foregroundWindow =
1646 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001647 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001648 sp<FakeWindowHandle> wallpaperWindow =
1649 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001650 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001651 constexpr int expectedWallpaperFlags =
1652 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1653
1654 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1655 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1656 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1657 {100, 200}))
1658 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1659
1660 // Both foreground window and its wallpaper should receive the touch down
1661 foregroundWindow->consumeMotionDown();
1662 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1663
1664 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1665 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1666 ADISPLAY_ID_DEFAULT, {110, 200}))
1667 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1668
1669 foregroundWindow->consumeMotionMove();
1670 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1671
1672 // Now the foreground window goes away, but the wallpaper stays
1673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1674 foregroundWindow->consumeMotionCancel();
1675 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1676 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1677}
1678
1679/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001680 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1681 * with the following differences:
1682 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1683 * clean up the connection.
1684 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1685 * Ensure that there's no crash in the dispatcher.
1686 */
1687TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1688 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1689 sp<FakeWindowHandle> foregroundWindow =
1690 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001691 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001692 sp<FakeWindowHandle> wallpaperWindow =
1693 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001694 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001695 constexpr int expectedWallpaperFlags =
1696 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1697
1698 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1699 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1700 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1701 {100, 200}))
1702 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1703
1704 // Both foreground window and its wallpaper should receive the touch down
1705 foregroundWindow->consumeMotionDown();
1706 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1707
1708 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1709 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1710 ADISPLAY_ID_DEFAULT, {110, 200}))
1711 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1712
1713 foregroundWindow->consumeMotionMove();
1714 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1715
1716 // Wallpaper closes its channel, but the window remains.
1717 wallpaperWindow->destroyReceiver();
1718 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1719
1720 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1721 // is no longer valid.
1722 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1723 foregroundWindow->consumeMotionCancel();
1724}
1725
1726/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001727 * A single window that receives touch (on top), and a wallpaper window underneath it.
1728 * The top window gets a multitouch gesture.
1729 * Ensure that wallpaper gets the same gesture.
1730 */
1731TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1732 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1733 sp<FakeWindowHandle> window =
1734 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001735 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001736
1737 sp<FakeWindowHandle> wallpaperWindow =
1738 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001739 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001740 constexpr int expectedWallpaperFlags =
1741 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1742
1743 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1744
1745 // Touch down on top window
1746 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1747 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1748 {100, 100}))
1749 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1750
1751 // Both top window and its wallpaper should receive the touch down
1752 window->consumeMotionDown();
1753 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1754
1755 // Second finger down on the top window
1756 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001757 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001758 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1759 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1760 .x(100)
1761 .y(100))
1762 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1763 .x(150)
1764 .y(150))
1765 .build();
1766 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1767 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1768 InputEventInjectionSync::WAIT_FOR_RESULT))
1769 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1770
1771 window->consumeMotionPointerDown(1 /* pointerIndex */);
1772 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1773 expectedWallpaperFlags);
1774 window->assertNoEvents();
1775 wallpaperWindow->assertNoEvents();
1776}
1777
1778/**
1779 * Two windows: a window on the left and window on the right.
1780 * A third window, wallpaper, is behind both windows, and spans both top windows.
1781 * The first touch down goes to the left window. A second pointer touches down on the right window.
1782 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1783 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1784 * ACTION_POINTER_DOWN(1).
1785 */
1786TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1787 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1788 sp<FakeWindowHandle> leftWindow =
1789 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1790 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001791 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001792
1793 sp<FakeWindowHandle> rightWindow =
1794 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1795 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001796 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001797
1798 sp<FakeWindowHandle> wallpaperWindow =
1799 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1800 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001801 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001802 constexpr int expectedWallpaperFlags =
1803 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1804
1805 mDispatcher->setInputWindows(
1806 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1807
1808 // Touch down on left window
1809 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1810 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1811 {100, 100}))
1812 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1813
1814 // Both foreground window and its wallpaper should receive the touch down
1815 leftWindow->consumeMotionDown();
1816 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1817
1818 // Second finger down on the right window
1819 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001820 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001821 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1822 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1823 .x(100)
1824 .y(100))
1825 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1826 .x(300)
1827 .y(100))
1828 .build();
1829 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1830 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1831 InputEventInjectionSync::WAIT_FOR_RESULT))
1832 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1833
1834 leftWindow->consumeMotionMove();
1835 // Since the touch is split, right window gets ACTION_DOWN
1836 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1837 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1838 expectedWallpaperFlags);
1839
1840 // Now, leftWindow, which received the first finger, disappears.
1841 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1842 leftWindow->consumeMotionCancel();
1843 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1844 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1845
1846 // The pointer that's still down on the right window moves, and goes to the right window only.
1847 // As far as the dispatcher's concerned though, both pointers are still present.
1848 const MotionEvent secondFingerMoveEvent =
1849 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1850 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1851 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1852 .x(100)
1853 .y(100))
1854 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1855 .x(310)
1856 .y(110))
1857 .build();
1858 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1859 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1860 InputEventInjectionSync::WAIT_FOR_RESULT));
1861 rightWindow->consumeMotionMove();
1862
1863 leftWindow->assertNoEvents();
1864 rightWindow->assertNoEvents();
1865 wallpaperWindow->assertNoEvents();
1866}
1867
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001868/**
1869 * On the display, have a single window, and also an area where there's no window.
1870 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
1871 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
1872 */
1873TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
1874 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1875 sp<FakeWindowHandle> window =
1876 new FakeWindowHandle(application, mDispatcher, "Window", DISPLAY_ID);
1877
1878 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
1879 NotifyMotionArgs args;
1880
1881 // Touch down on the empty space
1882 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
1883
1884 mDispatcher->waitForIdle();
1885 window->assertNoEvents();
1886
1887 // Now touch down on the window with another pointer
1888 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
1889 mDispatcher->waitForIdle();
1890 window->consumeMotionDown();
1891}
1892
1893/**
1894 * Same test as above, but instead of touching the empty space, the first touch goes to
1895 * non-touchable window.
1896 */
1897TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
1898 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1899 sp<FakeWindowHandle> window1 =
1900 new FakeWindowHandle(application, mDispatcher, "Window1", DISPLAY_ID);
1901 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1902 window1->setTouchable(false);
1903 sp<FakeWindowHandle> window2 =
1904 new FakeWindowHandle(application, mDispatcher, "Window2", DISPLAY_ID);
1905 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1906
1907 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1908
1909 NotifyMotionArgs args;
1910 // Touch down on the non-touchable window
1911 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1912
1913 mDispatcher->waitForIdle();
1914 window1->assertNoEvents();
1915 window2->assertNoEvents();
1916
1917 // Now touch down on the window with another pointer
1918 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1919 mDispatcher->waitForIdle();
1920 window2->consumeMotionDown();
1921}
1922
Garfield Tandf26e862020-07-01 20:18:19 -07001923TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001924 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001925 sp<FakeWindowHandle> windowLeft =
1926 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1927 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001928 sp<FakeWindowHandle> windowRight =
1929 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1930 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001931
1932 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1933
1934 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1935
1936 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001937 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001938 injectMotionEvent(mDispatcher,
1939 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1940 AINPUT_SOURCE_MOUSE)
1941 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1942 .x(900)
1943 .y(400))
1944 .build()));
1945 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1946 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1947 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1948 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1949
1950 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001951 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001952 injectMotionEvent(mDispatcher,
1953 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1954 AINPUT_SOURCE_MOUSE)
1955 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1956 .x(300)
1957 .y(400))
1958 .build()));
1959 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1960 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1961 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1962 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1963 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1964 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1965
1966 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001967 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001968 injectMotionEvent(mDispatcher,
1969 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1970 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1971 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1972 .x(300)
1973 .y(400))
1974 .build()));
1975 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1976
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001977 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001978 injectMotionEvent(mDispatcher,
1979 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1980 AINPUT_SOURCE_MOUSE)
1981 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1982 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1983 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1984 .x(300)
1985 .y(400))
1986 .build()));
1987 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1988 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
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_RELEASE,
1993 AINPUT_SOURCE_MOUSE)
1994 .buttonState(0)
1995 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1996 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1997 .x(300)
1998 .y(400))
1999 .build()));
2000 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
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_UP, AINPUT_SOURCE_MOUSE)
2006 .buttonState(0)
2007 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2008 .x(300)
2009 .y(400))
2010 .build()));
2011 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2012
2013 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002014 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002015 injectMotionEvent(mDispatcher,
2016 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2017 AINPUT_SOURCE_MOUSE)
2018 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2019 .x(900)
2020 .y(400))
2021 .build()));
2022 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2023 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2024 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2025 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2026 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2027 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2028}
2029
2030// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2031// directly in this test.
2032TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002033 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002034 sp<FakeWindowHandle> window =
2035 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2036 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002037
2038 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2039
2040 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2041
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002042 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002043 injectMotionEvent(mDispatcher,
2044 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2045 AINPUT_SOURCE_MOUSE)
2046 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2047 .x(300)
2048 .y(400))
2049 .build()));
2050 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2051 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2052
2053 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002054 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002055 injectMotionEvent(mDispatcher,
2056 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2057 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2058 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2059 .x(300)
2060 .y(400))
2061 .build()));
2062 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2063
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002064 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002065 injectMotionEvent(mDispatcher,
2066 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2067 AINPUT_SOURCE_MOUSE)
2068 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2069 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2070 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2071 .x(300)
2072 .y(400))
2073 .build()));
2074 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2075 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2076
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002077 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002078 injectMotionEvent(mDispatcher,
2079 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2080 AINPUT_SOURCE_MOUSE)
2081 .buttonState(0)
2082 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2083 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2084 .x(300)
2085 .y(400))
2086 .build()));
2087 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2088 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2089
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002090 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002091 injectMotionEvent(mDispatcher,
2092 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2093 .buttonState(0)
2094 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2095 .x(300)
2096 .y(400))
2097 .build()));
2098 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2099
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002100 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002101 injectMotionEvent(mDispatcher,
2102 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2103 AINPUT_SOURCE_MOUSE)
2104 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2105 .x(300)
2106 .y(400))
2107 .build()));
2108 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2109 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2110}
2111
Garfield Tan00f511d2019-06-12 16:55:40 -07002112TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002113 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002114
2115 sp<FakeWindowHandle> windowLeft =
2116 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2117 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002118 sp<FakeWindowHandle> windowRight =
2119 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2120 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002121
2122 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2123
Arthur Hung72d8dc32020-03-28 00:48:39 +00002124 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002125
2126 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2127 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002128 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002129 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002130 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002131 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002132 windowRight->assertNoEvents();
2133}
2134
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002135TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002136 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002137 sp<FakeWindowHandle> window =
2138 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002139 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002140
Arthur Hung72d8dc32020-03-28 00:48:39 +00002141 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002142 setFocusedWindow(window);
2143
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002144 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002145
2146 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2147 mDispatcher->notifyKey(&keyArgs);
2148
2149 // Window should receive key down event.
2150 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2151
2152 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2153 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002154 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002155 mDispatcher->notifyDeviceReset(&args);
2156 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2157 AKEY_EVENT_FLAG_CANCELED);
2158}
2159
2160TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002161 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002162 sp<FakeWindowHandle> window =
2163 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2164
Arthur Hung72d8dc32020-03-28 00:48:39 +00002165 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002166
2167 NotifyMotionArgs motionArgs =
2168 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2169 ADISPLAY_ID_DEFAULT);
2170 mDispatcher->notifyMotion(&motionArgs);
2171
2172 // Window should receive motion down event.
2173 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2174
2175 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2176 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002177 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002178 mDispatcher->notifyDeviceReset(&args);
2179 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2180 0 /*expectedFlags*/);
2181}
2182
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002183/**
2184 * Ensure the correct coordinate spaces are used by InputDispatcher.
2185 *
2186 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2187 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2188 * space.
2189 */
2190class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2191public:
2192 void SetUp() override {
2193 InputDispatcherTest::SetUp();
2194 mDisplayInfos.clear();
2195 mWindowInfos.clear();
2196 }
2197
2198 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2199 gui::DisplayInfo info;
2200 info.displayId = displayId;
2201 info.transform = transform;
2202 mDisplayInfos.push_back(std::move(info));
2203 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2204 }
2205
2206 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2207 mWindowInfos.push_back(*windowHandle->getInfo());
2208 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2209 }
2210
2211 // Set up a test scenario where the display has a scaled projection and there are two windows
2212 // on the display.
2213 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2214 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2215 // respectively.
2216 ui::Transform displayTransform;
2217 displayTransform.set(2, 0, 0, 4);
2218 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2219
2220 std::shared_ptr<FakeApplicationHandle> application =
2221 std::make_shared<FakeApplicationHandle>();
2222
2223 // Add two windows to the display. Their frames are represented in the display space.
2224 sp<FakeWindowHandle> firstWindow =
2225 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002226 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2227 addWindow(firstWindow);
2228
2229 sp<FakeWindowHandle> secondWindow =
2230 new FakeWindowHandle(application, mDispatcher, "Second Window",
2231 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002232 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2233 addWindow(secondWindow);
2234 return {std::move(firstWindow), std::move(secondWindow)};
2235 }
2236
2237private:
2238 std::vector<gui::DisplayInfo> mDisplayInfos;
2239 std::vector<gui::WindowInfo> mWindowInfos;
2240};
2241
2242TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2243 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2244 // Send down to the first window. The point is represented in the display space. The point is
2245 // selected so that if the hit test was done with the transform applied to it, then it would
2246 // end up in the incorrect window.
2247 NotifyMotionArgs downMotionArgs =
2248 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2249 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2250 mDispatcher->notifyMotion(&downMotionArgs);
2251
2252 firstWindow->consumeMotionDown();
2253 secondWindow->assertNoEvents();
2254}
2255
2256// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2257// the event should be treated as being in the logical display space.
2258TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2259 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2260 // Send down to the first window. The point is represented in the logical display space. The
2261 // point is selected so that if the hit test was done in logical display space, then it would
2262 // end up in the incorrect window.
2263 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2264 PointF{75 * 2, 55 * 4});
2265
2266 firstWindow->consumeMotionDown();
2267 secondWindow->assertNoEvents();
2268}
2269
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002270// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2271// event should be treated as being in the logical display space.
2272TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2273 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2274
2275 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2276 ui::Transform injectedEventTransform;
2277 injectedEventTransform.set(matrix);
2278 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2279 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2280
2281 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2282 .displayId(ADISPLAY_ID_DEFAULT)
2283 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2284 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2285 .x(untransformedPoint.x)
2286 .y(untransformedPoint.y))
2287 .build();
2288 event.transform(matrix);
2289
2290 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2291 InputEventInjectionSync::WAIT_FOR_RESULT);
2292
2293 firstWindow->consumeMotionDown();
2294 secondWindow->assertNoEvents();
2295}
2296
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002297TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2298 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2299
2300 // Send down to the second window.
2301 NotifyMotionArgs downMotionArgs =
2302 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2303 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2304 mDispatcher->notifyMotion(&downMotionArgs);
2305
2306 firstWindow->assertNoEvents();
2307 const MotionEvent* event = secondWindow->consumeMotion();
2308 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2309
2310 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2311 EXPECT_EQ(300, event->getRawX(0));
2312 EXPECT_EQ(880, event->getRawY(0));
2313
2314 // Ensure that the x and y values are in the window's coordinate space.
2315 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2316 // the logical display space. This will be the origin of the window space.
2317 EXPECT_EQ(100, event->getX(0));
2318 EXPECT_EQ(80, event->getY(0));
2319}
2320
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002321using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2322 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002323
2324class TransferTouchFixture : public InputDispatcherTest,
2325 public ::testing::WithParamInterface<TransferFunction> {};
2326
2327TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002328 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002329
2330 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002331 sp<FakeWindowHandle> firstWindow =
2332 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2333 sp<FakeWindowHandle> secondWindow =
2334 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002335
2336 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002337 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002338
2339 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002340 NotifyMotionArgs downMotionArgs =
2341 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2342 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002343 mDispatcher->notifyMotion(&downMotionArgs);
2344 // Only the first window should get the down event
2345 firstWindow->consumeMotionDown();
2346 secondWindow->assertNoEvents();
2347
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002348 // Transfer touch to the second window
2349 TransferFunction f = GetParam();
2350 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2351 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002352 // The first window gets cancel and the second gets down
2353 firstWindow->consumeMotionCancel();
2354 secondWindow->consumeMotionDown();
2355
2356 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002357 NotifyMotionArgs upMotionArgs =
2358 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2359 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002360 mDispatcher->notifyMotion(&upMotionArgs);
2361 // The first window gets no events and the second gets up
2362 firstWindow->assertNoEvents();
2363 secondWindow->consumeMotionUp();
2364}
2365
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002366TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002367 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002368
2369 PointF touchPoint = {10, 10};
2370
2371 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002372 sp<FakeWindowHandle> firstWindow =
2373 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002374 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002375 sp<FakeWindowHandle> secondWindow =
2376 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002377 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002378
2379 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002380 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002381
2382 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002383 NotifyMotionArgs downMotionArgs =
2384 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2385 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002386 mDispatcher->notifyMotion(&downMotionArgs);
2387 // Only the first window should get the down event
2388 firstWindow->consumeMotionDown();
2389 secondWindow->assertNoEvents();
2390
2391 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002392 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002393 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002394 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002395 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2396 // Only the first window should get the pointer down event
2397 firstWindow->consumeMotionPointerDown(1);
2398 secondWindow->assertNoEvents();
2399
2400 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002401 TransferFunction f = GetParam();
2402 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2403 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002404 // The first window gets cancel and the second gets down and pointer down
2405 firstWindow->consumeMotionCancel();
2406 secondWindow->consumeMotionDown();
2407 secondWindow->consumeMotionPointerDown(1);
2408
2409 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002410 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002411 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002412 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002413 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2414 // The first window gets nothing and the second gets pointer up
2415 firstWindow->assertNoEvents();
2416 secondWindow->consumeMotionPointerUp(1);
2417
2418 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002419 NotifyMotionArgs upMotionArgs =
2420 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2421 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002422 mDispatcher->notifyMotion(&upMotionArgs);
2423 // The first window gets nothing and the second gets up
2424 firstWindow->assertNoEvents();
2425 secondWindow->consumeMotionUp();
2426}
2427
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002428// For the cases of single pointer touch and two pointers non-split touch, the api's
2429// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2430// for the case where there are multiple pointers split across several windows.
2431INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2432 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002433 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2434 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002435 return dispatcher->transferTouch(destChannelToken);
2436 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002437 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2438 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002439 return dispatcher->transferTouchFocus(from, to,
2440 false /*isDragAndDrop*/);
2441 }));
2442
Svet Ganov5d3bc372020-01-26 23:11:07 -08002443TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002444 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002445
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002446 sp<FakeWindowHandle> firstWindow =
2447 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002448 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002449
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002450 sp<FakeWindowHandle> secondWindow =
2451 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002452 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002453
2454 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002455 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002456
2457 PointF pointInFirst = {300, 200};
2458 PointF pointInSecond = {300, 600};
2459
2460 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002461 NotifyMotionArgs firstDownMotionArgs =
2462 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2463 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002464 mDispatcher->notifyMotion(&firstDownMotionArgs);
2465 // Only the first window should get the down event
2466 firstWindow->consumeMotionDown();
2467 secondWindow->assertNoEvents();
2468
2469 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002470 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002471 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002472 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002473 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 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2480 // The first window gets cancel and the new gets pointer down (it already saw down)
2481 firstWindow->consumeMotionCancel();
2482 secondWindow->consumeMotionPointerDown(1);
2483
2484 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002485 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002486 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002487 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002488 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2489 // The first window gets nothing and the second gets pointer up
2490 firstWindow->assertNoEvents();
2491 secondWindow->consumeMotionPointerUp(1);
2492
2493 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002494 NotifyMotionArgs upMotionArgs =
2495 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2496 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002497 mDispatcher->notifyMotion(&upMotionArgs);
2498 // The first window gets nothing and the second gets up
2499 firstWindow->assertNoEvents();
2500 secondWindow->consumeMotionUp();
2501}
2502
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002503// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2504// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2505// touch is not supported, so the touch should continue on those windows and the transferred-to
2506// window should get nothing.
2507TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2508 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2509
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002510 sp<FakeWindowHandle> firstWindow =
2511 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2512 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002513
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002514 sp<FakeWindowHandle> secondWindow =
2515 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2516 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002517
2518 // Add the windows to the dispatcher
2519 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2520
2521 PointF pointInFirst = {300, 200};
2522 PointF pointInSecond = {300, 600};
2523
2524 // Send down to the first window
2525 NotifyMotionArgs firstDownMotionArgs =
2526 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2527 ADISPLAY_ID_DEFAULT, {pointInFirst});
2528 mDispatcher->notifyMotion(&firstDownMotionArgs);
2529 // Only the first window should get the down event
2530 firstWindow->consumeMotionDown();
2531 secondWindow->assertNoEvents();
2532
2533 // Send down to the second window
2534 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002535 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002536 {pointInFirst, pointInSecond});
2537 mDispatcher->notifyMotion(&secondDownMotionArgs);
2538 // The first window gets a move and the second a down
2539 firstWindow->consumeMotionMove();
2540 secondWindow->consumeMotionDown();
2541
2542 // Transfer touch focus to the second window
2543 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2544 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2545 ASSERT_FALSE(transferred);
2546 firstWindow->assertNoEvents();
2547 secondWindow->assertNoEvents();
2548
2549 // The rest of the dispatch should proceed as normal
2550 // Send pointer up to the second window
2551 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002552 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002553 {pointInFirst, pointInSecond});
2554 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2555 // The first window gets MOVE and the second gets pointer up
2556 firstWindow->consumeMotionMove();
2557 secondWindow->consumeMotionUp();
2558
2559 // Send up event to the first window
2560 NotifyMotionArgs upMotionArgs =
2561 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2562 ADISPLAY_ID_DEFAULT);
2563 mDispatcher->notifyMotion(&upMotionArgs);
2564 // The first window gets nothing and the second gets up
2565 firstWindow->consumeMotionUp();
2566 secondWindow->assertNoEvents();
2567}
2568
Arthur Hungabbb9d82021-09-01 14:52:30 +00002569// This case will create two windows and one mirrored window on the default display and mirror
2570// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2571// the windows info of second display before default display.
2572TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2573 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2574 sp<FakeWindowHandle> firstWindowInPrimary =
2575 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2576 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002577 sp<FakeWindowHandle> secondWindowInPrimary =
2578 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2579 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002580
2581 sp<FakeWindowHandle> mirrorWindowInPrimary =
2582 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2583 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002584
2585 sp<FakeWindowHandle> firstWindowInSecondary =
2586 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2587 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002588
2589 sp<FakeWindowHandle> secondWindowInSecondary =
2590 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2591 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002592
2593 // Update window info, let it find window handle of second display first.
2594 mDispatcher->setInputWindows(
2595 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2596 {ADISPLAY_ID_DEFAULT,
2597 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2598
2599 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2600 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2601 {50, 50}))
2602 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2603
2604 // Window should receive motion event.
2605 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2606
2607 // Transfer touch focus
2608 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2609 secondWindowInPrimary->getToken()));
2610 // The first window gets cancel.
2611 firstWindowInPrimary->consumeMotionCancel();
2612 secondWindowInPrimary->consumeMotionDown();
2613
2614 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2615 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2616 ADISPLAY_ID_DEFAULT, {150, 50}))
2617 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2618 firstWindowInPrimary->assertNoEvents();
2619 secondWindowInPrimary->consumeMotionMove();
2620
2621 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2622 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2623 {150, 50}))
2624 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2625 firstWindowInPrimary->assertNoEvents();
2626 secondWindowInPrimary->consumeMotionUp();
2627}
2628
2629// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2630// 'transferTouch' api.
2631TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2632 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2633 sp<FakeWindowHandle> firstWindowInPrimary =
2634 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2635 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002636 sp<FakeWindowHandle> secondWindowInPrimary =
2637 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2638 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002639
2640 sp<FakeWindowHandle> mirrorWindowInPrimary =
2641 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2642 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002643
2644 sp<FakeWindowHandle> firstWindowInSecondary =
2645 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2646 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002647
2648 sp<FakeWindowHandle> secondWindowInSecondary =
2649 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2650 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002651
2652 // Update window info, let it find window handle of second display first.
2653 mDispatcher->setInputWindows(
2654 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2655 {ADISPLAY_ID_DEFAULT,
2656 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2657
2658 // Touch on second display.
2659 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2660 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2661 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2662
2663 // Window should receive motion event.
2664 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2665
2666 // Transfer touch focus
2667 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2668
2669 // The first window gets cancel.
2670 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2671 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2672
2673 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2674 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2675 SECOND_DISPLAY_ID, {150, 50}))
2676 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2677 firstWindowInPrimary->assertNoEvents();
2678 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2679
2680 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2681 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2682 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2683 firstWindowInPrimary->assertNoEvents();
2684 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2685}
2686
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002687TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002688 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002689 sp<FakeWindowHandle> window =
2690 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2691
Vishnu Nair47074b82020-08-14 11:54:47 -07002692 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002693 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002694 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002695
2696 window->consumeFocusEvent(true);
2697
2698 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2699 mDispatcher->notifyKey(&keyArgs);
2700
2701 // Window should receive key down event.
2702 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2703}
2704
2705TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002706 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002707 sp<FakeWindowHandle> window =
2708 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2709
Arthur Hung72d8dc32020-03-28 00:48:39 +00002710 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002711
2712 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2713 mDispatcher->notifyKey(&keyArgs);
2714 mDispatcher->waitForIdle();
2715
2716 window->assertNoEvents();
2717}
2718
2719// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2720TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002721 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002722 sp<FakeWindowHandle> window =
2723 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2724
Arthur Hung72d8dc32020-03-28 00:48:39 +00002725 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002726
2727 // Send key
2728 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2729 mDispatcher->notifyKey(&keyArgs);
2730 // Send motion
2731 NotifyMotionArgs motionArgs =
2732 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2733 ADISPLAY_ID_DEFAULT);
2734 mDispatcher->notifyMotion(&motionArgs);
2735
2736 // Window should receive only the motion event
2737 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2738 window->assertNoEvents(); // Key event or focus event will not be received
2739}
2740
arthurhungea3f4fc2020-12-21 23:18:53 +08002741TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2742 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2743
arthurhungea3f4fc2020-12-21 23:18:53 +08002744 sp<FakeWindowHandle> firstWindow =
2745 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2746 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08002747
arthurhungea3f4fc2020-12-21 23:18:53 +08002748 sp<FakeWindowHandle> secondWindow =
2749 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2750 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08002751
2752 // Add the windows to the dispatcher
2753 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2754
2755 PointF pointInFirst = {300, 200};
2756 PointF pointInSecond = {300, 600};
2757
2758 // Send down to the first window
2759 NotifyMotionArgs firstDownMotionArgs =
2760 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2761 ADISPLAY_ID_DEFAULT, {pointInFirst});
2762 mDispatcher->notifyMotion(&firstDownMotionArgs);
2763 // Only the first window should get the down event
2764 firstWindow->consumeMotionDown();
2765 secondWindow->assertNoEvents();
2766
2767 // Send down to the second window
2768 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002769 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08002770 {pointInFirst, pointInSecond});
2771 mDispatcher->notifyMotion(&secondDownMotionArgs);
2772 // The first window gets a move and the second a down
2773 firstWindow->consumeMotionMove();
2774 secondWindow->consumeMotionDown();
2775
2776 // Send pointer cancel to the second window
2777 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002778 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08002779 {pointInFirst, pointInSecond});
2780 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2781 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2782 // The first window gets move and the second gets cancel.
2783 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2784 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2785
2786 // Send up event.
2787 NotifyMotionArgs upMotionArgs =
2788 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2789 ADISPLAY_ID_DEFAULT);
2790 mDispatcher->notifyMotion(&upMotionArgs);
2791 // The first window gets up and the second gets nothing.
2792 firstWindow->consumeMotionUp();
2793 secondWindow->assertNoEvents();
2794}
2795
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002796TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2797 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2798
2799 sp<FakeWindowHandle> window =
2800 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2801 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2802 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2803 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2804 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2805
2806 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2807 window->assertNoEvents();
2808 mDispatcher->waitForIdle();
2809}
2810
chaviwd1c23182019-12-20 18:44:56 -08002811class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002812public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002813 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002814 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07002815 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002816 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002817 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002818 }
2819
chaviwd1c23182019-12-20 18:44:56 -08002820 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2821
2822 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2823 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2824 expectedDisplayId, expectedFlags);
2825 }
2826
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002827 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2828
2829 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2830
chaviwd1c23182019-12-20 18:44:56 -08002831 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2832 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2833 expectedDisplayId, expectedFlags);
2834 }
2835
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002836 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2837 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2838 expectedDisplayId, expectedFlags);
2839 }
2840
chaviwd1c23182019-12-20 18:44:56 -08002841 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2842 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2843 expectedDisplayId, expectedFlags);
2844 }
2845
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002846 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2847 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2848 expectedDisplayId, expectedFlags);
2849 }
2850
Arthur Hungfbfa5722021-11-16 02:45:54 +00002851 void consumeMotionPointerDown(int32_t pointerIdx) {
2852 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2853 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2854 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2855 0 /*expectedFlags*/);
2856 }
2857
Evan Rosky84f07f02021-04-16 10:42:42 -07002858 MotionEvent* consumeMotion() {
2859 InputEvent* event = mInputReceiver->consume();
2860 if (!event) {
2861 ADD_FAILURE() << "No event was produced";
2862 return nullptr;
2863 }
2864 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2865 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2866 return nullptr;
2867 }
2868 return static_cast<MotionEvent*>(event);
2869 }
2870
chaviwd1c23182019-12-20 18:44:56 -08002871 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2872
2873private:
2874 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002875};
2876
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002877using InputDispatcherMonitorTest = InputDispatcherTest;
2878
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002879/**
2880 * Two entities that receive touch: A window, and a global monitor.
2881 * The touch goes to the window, and then the window disappears.
2882 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2883 * for the monitor, as well.
2884 * 1. foregroundWindow
2885 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2886 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002887TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002888 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2889 sp<FakeWindowHandle> window =
2890 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2891
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002892 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002893
2894 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2895 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2896 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2897 {100, 200}))
2898 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2899
2900 // Both the foreground window and the global monitor should receive the touch down
2901 window->consumeMotionDown();
2902 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2903
2904 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2905 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2906 ADISPLAY_ID_DEFAULT, {110, 200}))
2907 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2908
2909 window->consumeMotionMove();
2910 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2911
2912 // Now the foreground window goes away
2913 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2914 window->consumeMotionCancel();
2915 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2916
2917 // If more events come in, there will be no more foreground window to send them to. This will
2918 // cause a cancel for the monitor, as well.
2919 ASSERT_EQ(InputEventInjectionResult::FAILED,
2920 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2921 ADISPLAY_ID_DEFAULT, {120, 200}))
2922 << "Injection should fail because the window was removed";
2923 window->assertNoEvents();
2924 // Global monitor now gets the cancel
2925 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2926}
2927
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002928TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002929 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002930 sp<FakeWindowHandle> window =
2931 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002932 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002933
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002934 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002935
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002936 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002937 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002938 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002939 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002940 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002941}
2942
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002943TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
2944 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002945
Chris Yea209fde2020-07-22 13:54:51 -07002946 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002947 sp<FakeWindowHandle> window =
2948 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002949 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002950
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002951 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002952 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002953 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002954 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002955 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002956
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002957 // Pilfer pointers from the monitor.
2958 // This should not do anything and the window should continue to receive events.
2959 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00002960
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002961 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002962 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2963 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002964 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002965
2966 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2967 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002968}
2969
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002970TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07002971 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2972 sp<FakeWindowHandle> window =
2973 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2974 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2975 window->setWindowOffset(20, 40);
2976 window->setWindowTransform(0, 1, -1, 0);
2977
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002978 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07002979
2980 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2981 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2982 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2983 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2984 MotionEvent* event = monitor.consumeMotion();
2985 // Even though window has transform, gesture monitor must not.
2986 ASSERT_EQ(ui::Transform(), event->getTransform());
2987}
2988
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002989TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002990 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002991 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00002992
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002993 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00002994 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002995 << "Injection should fail if there is a monitor, but no touchable window";
2996 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00002997}
2998
chaviw81e2bb92019-12-18 15:03:51 -08002999TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003000 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08003001 sp<FakeWindowHandle> window =
3002 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3003
Arthur Hung72d8dc32020-03-28 00:48:39 +00003004 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003005
3006 NotifyMotionArgs motionArgs =
3007 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3008 ADISPLAY_ID_DEFAULT);
3009
3010 mDispatcher->notifyMotion(&motionArgs);
3011 // Window should receive motion down event.
3012 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3013
3014 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003015 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003016 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3017 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3018 motionArgs.pointerCoords[0].getX() - 10);
3019
3020 mDispatcher->notifyMotion(&motionArgs);
3021 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3022 0 /*expectedFlags*/);
3023}
3024
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003025/**
3026 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3027 * the device default right away. In the test scenario, we check both the default value,
3028 * and the action of enabling / disabling.
3029 */
3030TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003031 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003032 sp<FakeWindowHandle> window =
3033 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003034 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003035
3036 // Set focused application.
3037 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003038 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003039
3040 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003041 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003042 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003043 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3044
3045 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003046 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003047 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003048 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3049
3050 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003051 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3052 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003053 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003054 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003055 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003056 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003057 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3058
3059 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003060 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003061 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003062 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3063
3064 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003065 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3066 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003067 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003068 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003069 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003070 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003071 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3072
3073 window->assertNoEvents();
3074}
3075
Gang Wange9087892020-01-07 12:17:14 -05003076TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003077 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003078 sp<FakeWindowHandle> window =
3079 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3080
3081 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003082 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003083
Arthur Hung72d8dc32020-03-28 00:48:39 +00003084 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003085 setFocusedWindow(window);
3086
Gang Wange9087892020-01-07 12:17:14 -05003087 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3088
3089 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3090 mDispatcher->notifyKey(&keyArgs);
3091
3092 InputEvent* event = window->consume();
3093 ASSERT_NE(event, nullptr);
3094
3095 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3096 ASSERT_NE(verified, nullptr);
3097 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3098
3099 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3100 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3101 ASSERT_EQ(keyArgs.source, verified->source);
3102 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3103
3104 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3105
3106 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003107 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003108 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003109 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3110 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3111 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3112 ASSERT_EQ(0, verifiedKey.repeatCount);
3113}
3114
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003115TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003116 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003117 sp<FakeWindowHandle> window =
3118 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3119
3120 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3121
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003122 ui::Transform transform;
3123 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3124
3125 gui::DisplayInfo displayInfo;
3126 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3127 displayInfo.transform = transform;
3128
3129 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003130
3131 NotifyMotionArgs motionArgs =
3132 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3133 ADISPLAY_ID_DEFAULT);
3134 mDispatcher->notifyMotion(&motionArgs);
3135
3136 InputEvent* event = window->consume();
3137 ASSERT_NE(event, nullptr);
3138
3139 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3140 ASSERT_NE(verified, nullptr);
3141 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3142
3143 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3144 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3145 EXPECT_EQ(motionArgs.source, verified->source);
3146 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3147
3148 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3149
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003150 const vec2 rawXY =
3151 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3152 motionArgs.pointerCoords[0].getXYValue());
3153 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3154 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003155 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003156 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003157 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003158 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3159 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3160}
3161
chaviw09c8d2d2020-08-24 15:48:26 -07003162/**
3163 * Ensure that separate calls to sign the same data are generating the same key.
3164 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3165 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3166 * tests.
3167 */
3168TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3169 KeyEvent event = getTestKeyEvent();
3170 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3171
3172 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3173 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3174 ASSERT_EQ(hmac1, hmac2);
3175}
3176
3177/**
3178 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3179 */
3180TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3181 KeyEvent event = getTestKeyEvent();
3182 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3183 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3184
3185 verifiedEvent.deviceId += 1;
3186 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3187
3188 verifiedEvent.source += 1;
3189 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3190
3191 verifiedEvent.eventTimeNanos += 1;
3192 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3193
3194 verifiedEvent.displayId += 1;
3195 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3196
3197 verifiedEvent.action += 1;
3198 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3199
3200 verifiedEvent.downTimeNanos += 1;
3201 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3202
3203 verifiedEvent.flags += 1;
3204 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3205
3206 verifiedEvent.keyCode += 1;
3207 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3208
3209 verifiedEvent.scanCode += 1;
3210 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3211
3212 verifiedEvent.metaState += 1;
3213 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3214
3215 verifiedEvent.repeatCount += 1;
3216 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3217}
3218
Vishnu Nair958da932020-08-21 17:12:37 -07003219TEST_F(InputDispatcherTest, SetFocusedWindow) {
3220 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3221 sp<FakeWindowHandle> windowTop =
3222 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3223 sp<FakeWindowHandle> windowSecond =
3224 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3225 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3226
3227 // Top window is also focusable but is not granted focus.
3228 windowTop->setFocusable(true);
3229 windowSecond->setFocusable(true);
3230 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3231 setFocusedWindow(windowSecond);
3232
3233 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003234 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3235 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003236
3237 // Focused window should receive event.
3238 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3239 windowTop->assertNoEvents();
3240}
3241
3242TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3243 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3244 sp<FakeWindowHandle> window =
3245 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3246 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3247
3248 window->setFocusable(true);
3249 // Release channel for window is no longer valid.
3250 window->releaseChannel();
3251 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3252 setFocusedWindow(window);
3253
3254 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003255 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3256 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003257
3258 // window channel is invalid, so it should not receive any input event.
3259 window->assertNoEvents();
3260}
3261
3262TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3263 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3264 sp<FakeWindowHandle> window =
3265 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003266 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003267 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3268
Vishnu Nair958da932020-08-21 17:12:37 -07003269 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3270 setFocusedWindow(window);
3271
3272 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003273 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3274 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003275
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003276 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003277 window->assertNoEvents();
3278}
3279
3280TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3281 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3282 sp<FakeWindowHandle> windowTop =
3283 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3284 sp<FakeWindowHandle> windowSecond =
3285 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3286 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3287
3288 windowTop->setFocusable(true);
3289 windowSecond->setFocusable(true);
3290 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3291 setFocusedWindow(windowTop);
3292 windowTop->consumeFocusEvent(true);
3293
3294 setFocusedWindow(windowSecond, windowTop);
3295 windowSecond->consumeFocusEvent(true);
3296 windowTop->consumeFocusEvent(false);
3297
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003298 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3299 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003300
3301 // Focused window should receive event.
3302 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3303}
3304
3305TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3306 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3307 sp<FakeWindowHandle> windowTop =
3308 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3309 sp<FakeWindowHandle> windowSecond =
3310 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3311 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3312
3313 windowTop->setFocusable(true);
3314 windowSecond->setFocusable(true);
3315 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3316 setFocusedWindow(windowSecond, windowTop);
3317
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003318 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3319 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003320
3321 // Event should be dropped.
3322 windowTop->assertNoEvents();
3323 windowSecond->assertNoEvents();
3324}
3325
3326TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3327 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3328 sp<FakeWindowHandle> window =
3329 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3330 sp<FakeWindowHandle> previousFocusedWindow =
3331 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3332 ADISPLAY_ID_DEFAULT);
3333 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3334
3335 window->setFocusable(true);
3336 previousFocusedWindow->setFocusable(true);
3337 window->setVisible(false);
3338 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3339 setFocusedWindow(previousFocusedWindow);
3340 previousFocusedWindow->consumeFocusEvent(true);
3341
3342 // Requesting focus on invisible window takes focus from currently focused window.
3343 setFocusedWindow(window);
3344 previousFocusedWindow->consumeFocusEvent(false);
3345
3346 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003347 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003348 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003349 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003350
3351 // Window does not get focus event or key down.
3352 window->assertNoEvents();
3353
3354 // Window becomes visible.
3355 window->setVisible(true);
3356 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3357
3358 // Window receives focus event.
3359 window->consumeFocusEvent(true);
3360 // Focused window receives key down.
3361 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3362}
3363
Vishnu Nair599f1412021-06-21 10:39:58 -07003364TEST_F(InputDispatcherTest, DisplayRemoved) {
3365 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3366 sp<FakeWindowHandle> window =
3367 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3368 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3369
3370 // window is granted focus.
3371 window->setFocusable(true);
3372 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3373 setFocusedWindow(window);
3374 window->consumeFocusEvent(true);
3375
3376 // When a display is removed window loses focus.
3377 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3378 window->consumeFocusEvent(false);
3379}
3380
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003381/**
3382 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3383 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3384 * of the 'slipperyEnterWindow'.
3385 *
3386 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3387 * a way so that the touched location is no longer covered by the top window.
3388 *
3389 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3390 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3391 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3392 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3393 * with ACTION_DOWN).
3394 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3395 * window moved itself away from the touched location and had Flag::SLIPPERY.
3396 *
3397 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3398 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3399 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3400 *
3401 * In this test, we ensure that the event received by the bottom window has
3402 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3403 */
3404TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3405 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3406 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3407
3408 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3409 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3410
3411 sp<FakeWindowHandle> slipperyExitWindow =
3412 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003413 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003414 // Make sure this one overlaps the bottom window
3415 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3416 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3417 // one. Windows with the same owner are not considered to be occluding each other.
3418 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3419
3420 sp<FakeWindowHandle> slipperyEnterWindow =
3421 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3422 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3423
3424 mDispatcher->setInputWindows(
3425 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3426
3427 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3428 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3429 ADISPLAY_ID_DEFAULT, {{50, 50}});
3430 mDispatcher->notifyMotion(&args);
3431 slipperyExitWindow->consumeMotionDown();
3432 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3433 mDispatcher->setInputWindows(
3434 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3435
3436 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3437 ADISPLAY_ID_DEFAULT, {{51, 51}});
3438 mDispatcher->notifyMotion(&args);
3439
3440 slipperyExitWindow->consumeMotionCancel();
3441
3442 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3443 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3444}
3445
Garfield Tan1c7bc862020-01-28 13:24:04 -08003446class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3447protected:
3448 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3449 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3450
Chris Yea209fde2020-07-22 13:54:51 -07003451 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003452 sp<FakeWindowHandle> mWindow;
3453
3454 virtual void SetUp() override {
3455 mFakePolicy = new FakeInputDispatcherPolicy();
3456 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003457 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003458 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3459 ASSERT_EQ(OK, mDispatcher->start());
3460
3461 setUpWindow();
3462 }
3463
3464 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003465 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003466 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3467
Vishnu Nair47074b82020-08-14 11:54:47 -07003468 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003469 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003470 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003471 mWindow->consumeFocusEvent(true);
3472 }
3473
Chris Ye2ad95392020-09-01 13:44:44 -07003474 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003475 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003476 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003477 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3478 mDispatcher->notifyKey(&keyArgs);
3479
3480 // Window should receive key down event.
3481 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3482 }
3483
3484 void expectKeyRepeatOnce(int32_t repeatCount) {
3485 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3486 InputEvent* repeatEvent = mWindow->consume();
3487 ASSERT_NE(nullptr, repeatEvent);
3488
3489 uint32_t eventType = repeatEvent->getType();
3490 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3491
3492 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3493 uint32_t eventAction = repeatKeyEvent->getAction();
3494 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3495 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3496 }
3497
Chris Ye2ad95392020-09-01 13:44:44 -07003498 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003499 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003500 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003501 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3502 mDispatcher->notifyKey(&keyArgs);
3503
3504 // Window should receive key down event.
3505 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3506 0 /*expectedFlags*/);
3507 }
3508};
3509
3510TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003511 sendAndConsumeKeyDown(1 /* deviceId */);
3512 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3513 expectKeyRepeatOnce(repeatCount);
3514 }
3515}
3516
3517TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3518 sendAndConsumeKeyDown(1 /* deviceId */);
3519 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3520 expectKeyRepeatOnce(repeatCount);
3521 }
3522 sendAndConsumeKeyDown(2 /* deviceId */);
3523 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003524 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3525 expectKeyRepeatOnce(repeatCount);
3526 }
3527}
3528
3529TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003530 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003531 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003532 sendAndConsumeKeyUp(1 /* deviceId */);
3533 mWindow->assertNoEvents();
3534}
3535
3536TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3537 sendAndConsumeKeyDown(1 /* deviceId */);
3538 expectKeyRepeatOnce(1 /*repeatCount*/);
3539 sendAndConsumeKeyDown(2 /* deviceId */);
3540 expectKeyRepeatOnce(1 /*repeatCount*/);
3541 // Stale key up from device 1.
3542 sendAndConsumeKeyUp(1 /* deviceId */);
3543 // Device 2 is still down, keep repeating
3544 expectKeyRepeatOnce(2 /*repeatCount*/);
3545 expectKeyRepeatOnce(3 /*repeatCount*/);
3546 // Device 2 key up
3547 sendAndConsumeKeyUp(2 /* deviceId */);
3548 mWindow->assertNoEvents();
3549}
3550
3551TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3552 sendAndConsumeKeyDown(1 /* deviceId */);
3553 expectKeyRepeatOnce(1 /*repeatCount*/);
3554 sendAndConsumeKeyDown(2 /* deviceId */);
3555 expectKeyRepeatOnce(1 /*repeatCount*/);
3556 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3557 sendAndConsumeKeyUp(2 /* deviceId */);
3558 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003559 mWindow->assertNoEvents();
3560}
3561
liushenxiang42232912021-05-21 20:24:09 +08003562TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3563 sendAndConsumeKeyDown(DEVICE_ID);
3564 expectKeyRepeatOnce(1 /*repeatCount*/);
3565 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3566 mDispatcher->notifyDeviceReset(&args);
3567 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3568 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3569 mWindow->assertNoEvents();
3570}
3571
Garfield Tan1c7bc862020-01-28 13:24:04 -08003572TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003573 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003574 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3575 InputEvent* repeatEvent = mWindow->consume();
3576 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3577 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3578 IdGenerator::getSource(repeatEvent->getId()));
3579 }
3580}
3581
3582TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003583 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003584
3585 std::unordered_set<int32_t> idSet;
3586 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3587 InputEvent* repeatEvent = mWindow->consume();
3588 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3589 int32_t id = repeatEvent->getId();
3590 EXPECT_EQ(idSet.end(), idSet.find(id));
3591 idSet.insert(id);
3592 }
3593}
3594
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003595/* Test InputDispatcher for MultiDisplay */
3596class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3597public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003598 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003599 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003600
Chris Yea209fde2020-07-22 13:54:51 -07003601 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003602 windowInPrimary =
3603 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003604
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003605 // Set focus window for primary display, but focused display would be second one.
3606 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003607 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003608 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003609 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003610 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003611
Chris Yea209fde2020-07-22 13:54:51 -07003612 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003613 windowInSecondary =
3614 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003615 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003616 // Set focus display to second one.
3617 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3618 // Set focus window for second display.
3619 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003620 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003621 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003622 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003623 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003624 }
3625
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003626 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003627 InputDispatcherTest::TearDown();
3628
Chris Yea209fde2020-07-22 13:54:51 -07003629 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003630 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003631 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003632 windowInSecondary.clear();
3633 }
3634
3635protected:
Chris Yea209fde2020-07-22 13:54:51 -07003636 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003637 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003638 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003639 sp<FakeWindowHandle> windowInSecondary;
3640};
3641
3642TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3643 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003644 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3645 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3646 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003647 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003648 windowInSecondary->assertNoEvents();
3649
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003650 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003651 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3652 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3653 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003654 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003655 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003656}
3657
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003658TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003659 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003660 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3661 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003662 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003663 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003664 windowInSecondary->assertNoEvents();
3665
3666 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003667 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003668 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003669 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003670 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003671
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003672 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003673 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003674
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003675 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003676 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3677 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003678
3679 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003680 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003681 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003682 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003683 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003684 windowInSecondary->assertNoEvents();
3685}
3686
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003687// Test per-display input monitors for motion event.
3688TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003689 FakeMonitorReceiver monitorInPrimary =
3690 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3691 FakeMonitorReceiver monitorInSecondary =
3692 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003693
3694 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003695 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3696 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3697 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003698 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003699 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003700 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003701 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003702
3703 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003704 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3705 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3706 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003707 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003708 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003709 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003710 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003711
3712 // Test inject a non-pointer motion event.
3713 // If specific a display, it will dispatch to the focused window of particular display,
3714 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003715 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3716 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3717 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003718 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003719 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003720 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003721 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003722}
3723
3724// Test per-display input monitors for key event.
3725TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003726 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003727 FakeMonitorReceiver monitorInPrimary =
3728 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3729 FakeMonitorReceiver monitorInSecondary =
3730 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003731
3732 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003733 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3734 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003735 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003736 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003737 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003738 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003739}
3740
Vishnu Nair958da932020-08-21 17:12:37 -07003741TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3742 sp<FakeWindowHandle> secondWindowInPrimary =
3743 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3744 secondWindowInPrimary->setFocusable(true);
3745 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3746 setFocusedWindow(secondWindowInPrimary);
3747 windowInPrimary->consumeFocusEvent(false);
3748 secondWindowInPrimary->consumeFocusEvent(true);
3749
3750 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003751 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3752 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003753 windowInPrimary->assertNoEvents();
3754 windowInSecondary->assertNoEvents();
3755 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3756}
3757
Arthur Hungdfd528e2021-12-08 13:23:04 +00003758TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3759 FakeMonitorReceiver monitorInPrimary =
3760 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3761 FakeMonitorReceiver monitorInSecondary =
3762 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3763
3764 // Test touch down on primary display.
3765 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3766 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3767 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3768 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3769 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3770
3771 // Test touch down on second display.
3772 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3773 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3774 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3775 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3776 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3777
3778 // Trigger cancel touch.
3779 mDispatcher->cancelCurrentTouch();
3780 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3781 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3782 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3783 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3784
3785 // Test inject a move motion event, no window/monitor should receive the event.
3786 ASSERT_EQ(InputEventInjectionResult::FAILED,
3787 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3788 ADISPLAY_ID_DEFAULT, {110, 200}))
3789 << "Inject motion event should return InputEventInjectionResult::FAILED";
3790 windowInPrimary->assertNoEvents();
3791 monitorInPrimary.assertNoEvents();
3792
3793 ASSERT_EQ(InputEventInjectionResult::FAILED,
3794 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3795 SECOND_DISPLAY_ID, {110, 200}))
3796 << "Inject motion event should return InputEventInjectionResult::FAILED";
3797 windowInSecondary->assertNoEvents();
3798 monitorInSecondary.assertNoEvents();
3799}
3800
Jackal Guof9696682018-10-05 12:23:23 +08003801class InputFilterTest : public InputDispatcherTest {
3802protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003803 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3804 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003805 NotifyMotionArgs motionArgs;
3806
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003807 motionArgs =
3808 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003809 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003810 motionArgs =
3811 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003812 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003813 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003814 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003815 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3816 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003817 } else {
3818 mFakePolicy->assertFilterInputEventWasNotCalled();
3819 }
3820 }
3821
3822 void testNotifyKey(bool expectToBeFiltered) {
3823 NotifyKeyArgs keyArgs;
3824
3825 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3826 mDispatcher->notifyKey(&keyArgs);
3827 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3828 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003829 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003830
3831 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003832 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003833 } else {
3834 mFakePolicy->assertFilterInputEventWasNotCalled();
3835 }
3836 }
3837};
3838
3839// Test InputFilter for MotionEvent
3840TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3841 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3842 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3843 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3844
3845 // Enable InputFilter
3846 mDispatcher->setInputFilterEnabled(true);
3847 // Test touch on both primary and second display, and check if both events are filtered.
3848 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3849 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3850
3851 // Disable InputFilter
3852 mDispatcher->setInputFilterEnabled(false);
3853 // Test touch on both primary and second display, and check if both events aren't filtered.
3854 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3855 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3856}
3857
3858// Test InputFilter for KeyEvent
3859TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3860 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3861 testNotifyKey(/*expectToBeFiltered*/ false);
3862
3863 // Enable InputFilter
3864 mDispatcher->setInputFilterEnabled(true);
3865 // Send a key event, and check if it is filtered.
3866 testNotifyKey(/*expectToBeFiltered*/ true);
3867
3868 // Disable InputFilter
3869 mDispatcher->setInputFilterEnabled(false);
3870 // Send a key event, and check if it isn't filtered.
3871 testNotifyKey(/*expectToBeFiltered*/ false);
3872}
3873
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003874// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3875// logical display coordinate space.
3876TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3877 ui::Transform firstDisplayTransform;
3878 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3879 ui::Transform secondDisplayTransform;
3880 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3881
3882 std::vector<gui::DisplayInfo> displayInfos(2);
3883 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3884 displayInfos[0].transform = firstDisplayTransform;
3885 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3886 displayInfos[1].transform = secondDisplayTransform;
3887
3888 mDispatcher->onWindowInfosChanged({}, displayInfos);
3889
3890 // Enable InputFilter
3891 mDispatcher->setInputFilterEnabled(true);
3892
3893 // Ensure the correct transforms are used for the displays.
3894 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3895 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3896}
3897
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003898class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3899protected:
3900 virtual void SetUp() override {
3901 InputDispatcherTest::SetUp();
3902
3903 /**
3904 * We don't need to enable input filter to test the injected event policy, but we enabled it
3905 * here to make the tests more realistic, since this policy only matters when inputfilter is
3906 * on.
3907 */
3908 mDispatcher->setInputFilterEnabled(true);
3909
3910 std::shared_ptr<InputApplicationHandle> application =
3911 std::make_shared<FakeApplicationHandle>();
3912 mWindow =
3913 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3914
3915 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3916 mWindow->setFocusable(true);
3917 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3918 setFocusedWindow(mWindow);
3919 mWindow->consumeFocusEvent(true);
3920 }
3921
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003922 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3923 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003924 KeyEvent event;
3925
3926 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3927 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3928 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3929 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3930 const int32_t additionalPolicyFlags =
3931 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3932 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3933 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3934 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3935 policyFlags | additionalPolicyFlags));
3936
3937 InputEvent* received = mWindow->consume();
3938 ASSERT_NE(nullptr, received);
3939 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003940 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3941 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3942 ASSERT_EQ(flags, keyEvent.getFlags());
3943 }
3944
3945 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3946 int32_t flags) {
3947 MotionEvent event;
3948 PointerProperties pointerProperties[1];
3949 PointerCoords pointerCoords[1];
3950 pointerProperties[0].clear();
3951 pointerProperties[0].id = 0;
3952 pointerCoords[0].clear();
3953 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3954 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3955
3956 ui::Transform identityTransform;
3957 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3958 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3959 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3960 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3961 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003962 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003963 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003964 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3965
3966 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3967 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3968 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3969 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3970 policyFlags | additionalPolicyFlags));
3971
3972 InputEvent* received = mWindow->consume();
3973 ASSERT_NE(nullptr, received);
3974 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3975 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3976 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3977 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003978 }
3979
3980private:
3981 sp<FakeWindowHandle> mWindow;
3982};
3983
3984TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003985 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3986 // filter. Without it, the event will no different from a regularly injected event, and the
3987 // injected device id will be overwritten.
3988 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3989 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003990}
3991
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003992TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003993 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003994 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3995 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3996}
3997
3998TEST_F(InputFilterInjectionPolicyTest,
3999 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4000 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4001 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4002 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004003}
4004
4005TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4006 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004007 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004008}
4009
chaviwfd6d3512019-03-25 13:23:49 -07004010class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004011 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004012 InputDispatcherTest::SetUp();
4013
Chris Yea209fde2020-07-22 13:54:51 -07004014 std::shared_ptr<FakeApplicationHandle> application =
4015 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004016 mUnfocusedWindow =
4017 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004018 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004019
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004020 mFocusedWindow =
4021 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4022 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004023
4024 // Set focused application.
4025 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004026 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004027
4028 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004029 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004030 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004031 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004032 }
4033
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004034 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004035 InputDispatcherTest::TearDown();
4036
4037 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004038 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004039 }
4040
4041protected:
4042 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004043 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004044 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004045};
4046
4047// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4048// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4049// the onPointerDownOutsideFocus callback.
4050TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004051 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004052 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4053 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004054 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004055 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004056
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004057 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004058 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4059}
4060
4061// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4062// DOWN on the window that doesn't have focus. Ensure no window received the
4063// onPointerDownOutsideFocus callback.
4064TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004065 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004066 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004067 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004068 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004069
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004070 ASSERT_TRUE(mDispatcher->waitForIdle());
4071 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004072}
4073
4074// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4075// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4076TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004077 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4078 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004079 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004080 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004081
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004082 ASSERT_TRUE(mDispatcher->waitForIdle());
4083 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004084}
4085
4086// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4087// DOWN on the window that already has focus. Ensure no window received the
4088// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004089TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004090 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004091 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004092 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004093 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004094 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004095
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004096 ASSERT_TRUE(mDispatcher->waitForIdle());
4097 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004098}
4099
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004100// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4101// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4102TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4103 const MotionEvent event =
4104 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4105 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4106 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4107 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4108 .build();
4109 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4110 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4111 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4112
4113 ASSERT_TRUE(mDispatcher->waitForIdle());
4114 mFakePolicy->assertOnPointerDownWasNotCalled();
4115 // Ensure that the unfocused window did not receive any FOCUS events.
4116 mUnfocusedWindow->assertNoEvents();
4117}
4118
chaviwaf87b3e2019-10-01 16:59:28 -07004119// These tests ensures we can send touch events to a single client when there are multiple input
4120// windows that point to the same client token.
4121class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4122 virtual void SetUp() override {
4123 InputDispatcherTest::SetUp();
4124
Chris Yea209fde2020-07-22 13:54:51 -07004125 std::shared_ptr<FakeApplicationHandle> application =
4126 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004127 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4128 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004129 mWindow1->setFrame(Rect(0, 0, 100, 100));
4130
4131 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4132 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004133 mWindow2->setFrame(Rect(100, 100, 200, 200));
4134
Arthur Hung72d8dc32020-03-28 00:48:39 +00004135 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004136 }
4137
4138protected:
4139 sp<FakeWindowHandle> mWindow1;
4140 sp<FakeWindowHandle> mWindow2;
4141
4142 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004143 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004144 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4145 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004146 }
4147
4148 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4149 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004150 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004151 InputEvent* event = window->consume();
4152
4153 ASSERT_NE(nullptr, event) << name.c_str()
4154 << ": consumer should have returned non-NULL event.";
4155
4156 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4157 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4158 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4159
4160 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004161 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004162
4163 for (size_t i = 0; i < points.size(); i++) {
4164 float expectedX = points[i].x;
4165 float expectedY = points[i].y;
4166
4167 EXPECT_EQ(expectedX, motionEvent.getX(i))
4168 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4169 << ", got " << motionEvent.getX(i);
4170 EXPECT_EQ(expectedY, motionEvent.getY(i))
4171 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4172 << ", got " << motionEvent.getY(i);
4173 }
4174 }
chaviw9eaa22c2020-07-01 16:21:27 -07004175
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004176 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004177 std::vector<PointF> expectedPoints) {
4178 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4179 ADISPLAY_ID_DEFAULT, touchedPoints);
4180 mDispatcher->notifyMotion(&motionArgs);
4181
4182 // Always consume from window1 since it's the window that has the InputReceiver
4183 consumeMotionEvent(mWindow1, action, expectedPoints);
4184 }
chaviwaf87b3e2019-10-01 16:59:28 -07004185};
4186
4187TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4188 // Touch Window 1
4189 PointF touchedPoint = {10, 10};
4190 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004191 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004192
4193 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004194 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004195
4196 // Touch Window 2
4197 touchedPoint = {150, 150};
4198 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004199 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004200}
4201
chaviw9eaa22c2020-07-01 16:21:27 -07004202TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4203 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004204 mWindow2->setWindowScale(0.5f, 0.5f);
4205
4206 // Touch Window 1
4207 PointF touchedPoint = {10, 10};
4208 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004209 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004210 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004211 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004212
4213 // Touch Window 2
4214 touchedPoint = {150, 150};
4215 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004216 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4217 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004218
chaviw9eaa22c2020-07-01 16:21:27 -07004219 // Update the transform so rotation is set
4220 mWindow2->setWindowTransform(0, -1, 1, 0);
4221 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4222 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004223}
4224
chaviw9eaa22c2020-07-01 16:21:27 -07004225TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004226 mWindow2->setWindowScale(0.5f, 0.5f);
4227
4228 // Touch Window 1
4229 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4230 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004231 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004232
4233 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004234 touchedPoints.push_back(PointF{150, 150});
4235 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004236 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004237
chaviw9eaa22c2020-07-01 16:21:27 -07004238 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004239 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004240 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004241
chaviw9eaa22c2020-07-01 16:21:27 -07004242 // Update the transform so rotation is set for Window 2
4243 mWindow2->setWindowTransform(0, -1, 1, 0);
4244 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004245 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004246}
4247
chaviw9eaa22c2020-07-01 16:21:27 -07004248TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004249 mWindow2->setWindowScale(0.5f, 0.5f);
4250
4251 // Touch Window 1
4252 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4253 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004254 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004255
4256 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004257 touchedPoints.push_back(PointF{150, 150});
4258 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004259
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004260 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004261
4262 // Move both windows
4263 touchedPoints = {{20, 20}, {175, 175}};
4264 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4265 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4266
chaviw9eaa22c2020-07-01 16:21:27 -07004267 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004268
chaviw9eaa22c2020-07-01 16:21:27 -07004269 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004270 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004271 expectedPoints.pop_back();
4272
4273 // Touch Window 2
4274 mWindow2->setWindowTransform(0, -1, 1, 0);
4275 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004276 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004277
4278 // Move both windows
4279 touchedPoints = {{20, 20}, {175, 175}};
4280 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4281 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4282
4283 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004284}
4285
4286TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4287 mWindow1->setWindowScale(0.5f, 0.5f);
4288
4289 // Touch Window 1
4290 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4291 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004292 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004293
4294 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004295 touchedPoints.push_back(PointF{150, 150});
4296 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004297
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004298 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004299
4300 // Move both windows
4301 touchedPoints = {{20, 20}, {175, 175}};
4302 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4303 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4304
chaviw9eaa22c2020-07-01 16:21:27 -07004305 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004306}
4307
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004308class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4309 virtual void SetUp() override {
4310 InputDispatcherTest::SetUp();
4311
Chris Yea209fde2020-07-22 13:54:51 -07004312 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004313 mApplication->setDispatchingTimeout(20ms);
4314 mWindow =
4315 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4316 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004317 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004318 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004319
4320 // Set focused application.
4321 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4322
4323 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004324 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004325 mWindow->consumeFocusEvent(true);
4326 }
4327
4328 virtual void TearDown() override {
4329 InputDispatcherTest::TearDown();
4330 mWindow.clear();
4331 }
4332
4333protected:
Chris Yea209fde2020-07-22 13:54:51 -07004334 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004335 sp<FakeWindowHandle> mWindow;
4336 static constexpr PointF WINDOW_LOCATION = {20, 20};
4337
4338 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004339 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004340 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4341 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004342 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004343 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4344 WINDOW_LOCATION));
4345 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004346
4347 sp<FakeWindowHandle> addSpyWindow() {
4348 sp<FakeWindowHandle> spy =
4349 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4350 spy->setTrustedOverlay(true);
4351 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004352 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004353 spy->setDispatchingTimeout(30ms);
4354 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4355 return spy;
4356 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004357};
4358
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004359// Send a tap and respond, which should not cause an ANR.
4360TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4361 tapOnWindow();
4362 mWindow->consumeMotionDown();
4363 mWindow->consumeMotionUp();
4364 ASSERT_TRUE(mDispatcher->waitForIdle());
4365 mFakePolicy->assertNotifyAnrWasNotCalled();
4366}
4367
4368// Send a regular key and respond, which should not cause an ANR.
4369TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004370 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004371 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4372 ASSERT_TRUE(mDispatcher->waitForIdle());
4373 mFakePolicy->assertNotifyAnrWasNotCalled();
4374}
4375
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004376TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4377 mWindow->setFocusable(false);
4378 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4379 mWindow->consumeFocusEvent(false);
4380
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004381 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004382 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004383 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4384 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004385 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004386 // Key will not go to window because we have no focused window.
4387 // The 'no focused window' ANR timer should start instead.
4388
4389 // Now, the focused application goes away.
4390 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4391 // The key should get dropped and there should be no ANR.
4392
4393 ASSERT_TRUE(mDispatcher->waitForIdle());
4394 mFakePolicy->assertNotifyAnrWasNotCalled();
4395}
4396
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004397// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004398// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4399// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004400TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004401 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004402 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4403 WINDOW_LOCATION));
4404
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004405 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4406 ASSERT_TRUE(sequenceNum);
4407 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004408 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004409
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004410 mWindow->finishEvent(*sequenceNum);
4411 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4412 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004413 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004414 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004415}
4416
4417// Send a key to the app and have the app not respond right away.
4418TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4419 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004420 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004421 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4422 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004423 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004424 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004425 ASSERT_TRUE(mDispatcher->waitForIdle());
4426}
4427
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004428// We have a focused application, but no focused window
4429TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004430 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004431 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4432 mWindow->consumeFocusEvent(false);
4433
4434 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004435 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004436 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4437 WINDOW_LOCATION));
4438 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4439 mDispatcher->waitForIdle();
4440 mFakePolicy->assertNotifyAnrWasNotCalled();
4441
4442 // Once a focused event arrives, we get an ANR for this application
4443 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4444 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004445 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004446 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004447 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004448 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004449 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004450 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004451 ASSERT_TRUE(mDispatcher->waitForIdle());
4452}
4453
4454// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004455// Make sure that we don't notify policy twice about the same ANR.
4456TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004457 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004458 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4459 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004460
4461 // Once a focused event arrives, we get an ANR for this application
4462 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4463 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004464 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004465 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004466 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004467 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004468 const std::chrono::duration appTimeout =
4469 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004470 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004471
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004472 std::this_thread::sleep_for(appTimeout);
4473 // ANR should not be raised again. It is up to policy to do that if it desires.
4474 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004475
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004476 // If we now get a focused window, the ANR should stop, but the policy handles that via
4477 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004478 ASSERT_TRUE(mDispatcher->waitForIdle());
4479}
4480
4481// We have a focused application, but no focused window
4482TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004483 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004484 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4485 mWindow->consumeFocusEvent(false);
4486
4487 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004488 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004489 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004490 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4491 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004492
4493 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004494 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004495
4496 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004497 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004498 ASSERT_TRUE(mDispatcher->waitForIdle());
4499 mWindow->assertNoEvents();
4500}
4501
4502/**
4503 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4504 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4505 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4506 * the ANR mechanism should still work.
4507 *
4508 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4509 * DOWN event, while not responding on the second one.
4510 */
4511TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4512 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4513 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4514 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4515 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4516 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004517 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004518
4519 // Now send ACTION_UP, with identical timestamp
4520 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4521 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4522 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4523 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004524 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004525
4526 // We have now sent down and up. Let's consume first event and then ANR on the second.
4527 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4528 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004529 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004530}
4531
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004532// A spy window can receive an ANR
4533TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4534 sp<FakeWindowHandle> spy = addSpyWindow();
4535
4536 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4537 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4538 WINDOW_LOCATION));
4539 mWindow->consumeMotionDown();
4540
4541 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4542 ASSERT_TRUE(sequenceNum);
4543 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004544 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004545
4546 spy->finishEvent(*sequenceNum);
4547 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4548 0 /*flags*/);
4549 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004550 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004551}
4552
4553// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004554// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004555TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4556 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004557
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004558 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4559 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004560 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004561 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004562
4563 // Stuck on the ACTION_UP
4564 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004565 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004566
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004567 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004568 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004569 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4570 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004571
4572 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4573 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004574 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004575 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004576 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004577}
4578
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004579// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004580// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004581TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4582 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004583
4584 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004585 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4586 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004587
4588 mWindow->consumeMotionDown();
4589 // Stuck on the 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
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004593 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004594 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004595 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4596 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004597
4598 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4599 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004600 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004601 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004602 spy->assertNoEvents();
4603}
4604
4605TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4606 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4607
4608 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4609
4610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4611 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4612 WINDOW_LOCATION));
4613
4614 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4615 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4616 ASSERT_TRUE(consumeSeq);
4617
Prabir Pradhanedd96402022-02-15 01:46:16 -08004618 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004619
4620 monitor.finishEvent(*consumeSeq);
4621 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4622
4623 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004624 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004625}
4626
4627// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4628// process events, you don't get an anr. When the window later becomes unresponsive again, you
4629// get an ANR again.
4630// 1. tap -> block on ACTION_UP -> receive ANR
4631// 2. consume all pending events (= queue becomes healthy again)
4632// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4633TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4634 tapOnWindow();
4635
4636 mWindow->consumeMotionDown();
4637 // Block on ACTION_UP
4638 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004639 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004640 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4641 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004642 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004643 mWindow->assertNoEvents();
4644
4645 tapOnWindow();
4646 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004647 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004648 mWindow->consumeMotionUp();
4649
4650 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004651 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004652 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004653 mWindow->assertNoEvents();
4654}
4655
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004656// If a connection remains unresponsive for a while, make sure policy is only notified once about
4657// it.
4658TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004659 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004660 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4661 WINDOW_LOCATION));
4662
4663 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004664 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004665 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004666 // 'notifyConnectionUnresponsive' should only be called once per connection
4667 mFakePolicy->assertNotifyAnrWasNotCalled();
4668 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004669 mWindow->consumeMotionDown();
4670 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4671 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4672 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004673 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004674 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004675 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004676}
4677
4678/**
4679 * If a window is processing a motion event, and then a key event comes in, the key event should
4680 * not to to the focused window until the motion is processed.
4681 *
4682 * Warning!!!
4683 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4684 * and the injection timeout that we specify when injecting the key.
4685 * We must have the injection timeout (10ms) be smaller than
4686 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4687 *
4688 * If that value changes, this test should also change.
4689 */
4690TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4691 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4692 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4693
4694 tapOnWindow();
4695 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4696 ASSERT_TRUE(downSequenceNum);
4697 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4698 ASSERT_TRUE(upSequenceNum);
4699 // Don't finish the events yet, and send a key
4700 // Injection will "succeed" because we will eventually give up and send the key to the focused
4701 // window even if motions are still being processed. But because the injection timeout is short,
4702 // we will receive INJECTION_TIMED_OUT as the result.
4703
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004704 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004705 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004706 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4707 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004708 // Key will not be sent to the window, yet, because the window is still processing events
4709 // and the key remains pending, waiting for the touch events to be processed
4710 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4711 ASSERT_FALSE(keySequenceNum);
4712
4713 std::this_thread::sleep_for(500ms);
4714 // if we wait long enough though, dispatcher will give up, and still send the key
4715 // to the focused window, even though we have not yet finished the motion event
4716 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4717 mWindow->finishEvent(*downSequenceNum);
4718 mWindow->finishEvent(*upSequenceNum);
4719}
4720
4721/**
4722 * If a window is processing a motion event, and then a key event comes in, the key event should
4723 * not go to the focused window until the motion is processed.
4724 * If then a new motion comes in, then the pending key event should be going to the currently
4725 * focused window right away.
4726 */
4727TEST_F(InputDispatcherSingleWindowAnr,
4728 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4729 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4730 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4731
4732 tapOnWindow();
4733 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4734 ASSERT_TRUE(downSequenceNum);
4735 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4736 ASSERT_TRUE(upSequenceNum);
4737 // Don't finish the events yet, and send a key
4738 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004739 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004740 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004741 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004742 // At this point, key is still pending, and should not be sent to the application yet.
4743 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4744 ASSERT_FALSE(keySequenceNum);
4745
4746 // Now tap down again. It should cause the pending key to go to the focused window right away.
4747 tapOnWindow();
4748 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4749 // the other events yet. We can finish events in any order.
4750 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4751 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4752 mWindow->consumeMotionDown();
4753 mWindow->consumeMotionUp();
4754 mWindow->assertNoEvents();
4755}
4756
4757class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4758 virtual void SetUp() override {
4759 InputDispatcherTest::SetUp();
4760
Chris Yea209fde2020-07-22 13:54:51 -07004761 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004762 mApplication->setDispatchingTimeout(10ms);
4763 mUnfocusedWindow =
4764 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4765 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004766 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004767 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004768
4769 mFocusedWindow =
4770 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004771 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004772 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004773
4774 // Set focused application.
4775 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004776 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004777
4778 // Expect one focus window exist in display.
4779 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004780 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004781 mFocusedWindow->consumeFocusEvent(true);
4782 }
4783
4784 virtual void TearDown() override {
4785 InputDispatcherTest::TearDown();
4786
4787 mUnfocusedWindow.clear();
4788 mFocusedWindow.clear();
4789 }
4790
4791protected:
Chris Yea209fde2020-07-22 13:54:51 -07004792 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004793 sp<FakeWindowHandle> mUnfocusedWindow;
4794 sp<FakeWindowHandle> mFocusedWindow;
4795 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4796 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4797 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4798
4799 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4800
4801 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4802
4803private:
4804 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004805 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004806 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4807 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004808 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004809 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4810 location));
4811 }
4812};
4813
4814// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4815// should be ANR'd first.
4816TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004817 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004818 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4819 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004820 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004821 mFocusedWindow->consumeMotionDown();
4822 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4823 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4824 // We consumed all events, so no ANR
4825 ASSERT_TRUE(mDispatcher->waitForIdle());
4826 mFakePolicy->assertNotifyAnrWasNotCalled();
4827
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004828 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004829 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4830 FOCUSED_WINDOW_LOCATION));
4831 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4832 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004833
4834 const std::chrono::duration timeout =
4835 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004836 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004837 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4838 // sequence to make it consistent
4839 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004840 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004841 mFocusedWindow->consumeMotionDown();
4842 // This cancel is generated because the connection was unresponsive
4843 mFocusedWindow->consumeMotionCancel();
4844 mFocusedWindow->assertNoEvents();
4845 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004846 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004847 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
4848 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004849 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004850}
4851
4852// If we have 2 windows with identical timeouts that are both unresponsive,
4853// it doesn't matter which order they should have ANR.
4854// But we should receive ANR for both.
4855TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4856 // Set the timeout for unfocused window to match the focused window
4857 mUnfocusedWindow->setDispatchingTimeout(10ms);
4858 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4859
4860 tapOnFocusedWindow();
4861 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08004862 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
4863 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
4864 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004865
4866 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004867 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4868 mFocusedWindow->getToken() == anrConnectionToken2);
4869 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4870 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004871
4872 ASSERT_TRUE(mDispatcher->waitForIdle());
4873 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004874
4875 mFocusedWindow->consumeMotionDown();
4876 mFocusedWindow->consumeMotionUp();
4877 mUnfocusedWindow->consumeMotionOutside();
4878
Prabir Pradhanedd96402022-02-15 01:46:16 -08004879 sp<IBinder> responsiveToken1, responsiveToken2;
4880 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
4881 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004882
4883 // Both applications should be marked as responsive, in any order
4884 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4885 mFocusedWindow->getToken() == responsiveToken2);
4886 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4887 mUnfocusedWindow->getToken() == responsiveToken2);
4888 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004889}
4890
4891// If a window is already not responding, the second tap on the same window should be ignored.
4892// We should also log an error to account for the dropped event (not tested here).
4893// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4894TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4895 tapOnFocusedWindow();
4896 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4897 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4898 // Receive the events, but don't respond
4899 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4900 ASSERT_TRUE(downEventSequenceNum);
4901 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4902 ASSERT_TRUE(upEventSequenceNum);
4903 const std::chrono::duration timeout =
4904 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004905 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004906
4907 // Tap once again
4908 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004909 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004910 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4911 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004912 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004913 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4914 FOCUSED_WINDOW_LOCATION));
4915 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4916 // valid touch target
4917 mUnfocusedWindow->assertNoEvents();
4918
4919 // Consume the first tap
4920 mFocusedWindow->finishEvent(*downEventSequenceNum);
4921 mFocusedWindow->finishEvent(*upEventSequenceNum);
4922 ASSERT_TRUE(mDispatcher->waitForIdle());
4923 // The second tap did not go to the focused window
4924 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004925 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08004926 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
4927 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004928 mFakePolicy->assertNotifyAnrWasNotCalled();
4929}
4930
4931// If you tap outside of all windows, there will not be ANR
4932TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004933 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004934 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4935 LOCATION_OUTSIDE_ALL_WINDOWS));
4936 ASSERT_TRUE(mDispatcher->waitForIdle());
4937 mFakePolicy->assertNotifyAnrWasNotCalled();
4938}
4939
4940// Since the focused window is paused, tapping on it should not produce any events
4941TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4942 mFocusedWindow->setPaused(true);
4943 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4944
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004945 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004946 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4947 FOCUSED_WINDOW_LOCATION));
4948
4949 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4950 ASSERT_TRUE(mDispatcher->waitForIdle());
4951 // Should not ANR because the window is paused, and touches shouldn't go to it
4952 mFakePolicy->assertNotifyAnrWasNotCalled();
4953
4954 mFocusedWindow->assertNoEvents();
4955 mUnfocusedWindow->assertNoEvents();
4956}
4957
4958/**
4959 * If a window is processing a motion event, and then a key event comes in, the key event should
4960 * not to to the focused window until the motion is processed.
4961 * If a different window becomes focused at this time, the key should go to that window instead.
4962 *
4963 * Warning!!!
4964 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4965 * and the injection timeout that we specify when injecting the key.
4966 * We must have the injection timeout (10ms) be smaller than
4967 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4968 *
4969 * If that value changes, this test should also change.
4970 */
4971TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4972 // Set a long ANR timeout to prevent it from triggering
4973 mFocusedWindow->setDispatchingTimeout(2s);
4974 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4975
4976 tapOnUnfocusedWindow();
4977 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4978 ASSERT_TRUE(downSequenceNum);
4979 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4980 ASSERT_TRUE(upSequenceNum);
4981 // Don't finish the events yet, and send a key
4982 // Injection will succeed because we will eventually give up and send the key to the focused
4983 // window even if motions are still being processed.
4984
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004985 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004986 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004987 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4988 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004989 // Key will not be sent to the window, yet, because the window is still processing events
4990 // and the key remains pending, waiting for the touch events to be processed
4991 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4992 ASSERT_FALSE(keySequenceNum);
4993
4994 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004995 mFocusedWindow->setFocusable(false);
4996 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004997 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004998 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004999
5000 // Focus events should precede the key events
5001 mUnfocusedWindow->consumeFocusEvent(true);
5002 mFocusedWindow->consumeFocusEvent(false);
5003
5004 // Finish the tap events, which should unblock dispatcher
5005 mUnfocusedWindow->finishEvent(*downSequenceNum);
5006 mUnfocusedWindow->finishEvent(*upSequenceNum);
5007
5008 // Now that all queues are cleared and no backlog in the connections, the key event
5009 // can finally go to the newly focused "mUnfocusedWindow".
5010 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5011 mFocusedWindow->assertNoEvents();
5012 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005013 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005014}
5015
5016// When the touch stream is split across 2 windows, and one of them does not respond,
5017// then ANR should be raised and the touch should be canceled for the unresponsive window.
5018// The other window should not be affected by that.
5019TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5020 // Touch Window 1
5021 NotifyMotionArgs motionArgs =
5022 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5023 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5024 mDispatcher->notifyMotion(&motionArgs);
5025 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5026 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5027
5028 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005029 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5030 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005031 mDispatcher->notifyMotion(&motionArgs);
5032
5033 const std::chrono::duration timeout =
5034 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005035 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005036
5037 mUnfocusedWindow->consumeMotionDown();
5038 mFocusedWindow->consumeMotionDown();
5039 // Focused window may or may not receive ACTION_MOVE
5040 // But it should definitely receive ACTION_CANCEL due to the ANR
5041 InputEvent* event;
5042 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5043 ASSERT_TRUE(moveOrCancelSequenceNum);
5044 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5045 ASSERT_NE(nullptr, event);
5046 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5047 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5048 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5049 mFocusedWindow->consumeMotionCancel();
5050 } else {
5051 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5052 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005053 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005054 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5055 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005056
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005057 mUnfocusedWindow->assertNoEvents();
5058 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005059 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005060}
5061
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005062/**
5063 * If we have no focused window, and a key comes in, we start the ANR timer.
5064 * The focused application should add a focused window before the timer runs out to prevent ANR.
5065 *
5066 * If the user touches another application during this time, the key should be dropped.
5067 * Next, if a new focused window comes in, without toggling the focused application,
5068 * then no ANR should occur.
5069 *
5070 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5071 * but in some cases the policy may not update the focused application.
5072 */
5073TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5074 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5075 std::make_shared<FakeApplicationHandle>();
5076 focusedApplication->setDispatchingTimeout(60ms);
5077 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5078 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5079 mFocusedWindow->setFocusable(false);
5080
5081 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5082 mFocusedWindow->consumeFocusEvent(false);
5083
5084 // Send a key. The ANR timer should start because there is no focused window.
5085 // 'focusedApplication' will get blamed if this timer completes.
5086 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005087 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005088 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005089 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5090 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005091 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005092
5093 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5094 // then the injected touches won't cause the focused event to get dropped.
5095 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5096 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5097 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5098 // For this test, it means that the key would get delivered to the window once it becomes
5099 // focused.
5100 std::this_thread::sleep_for(10ms);
5101
5102 // Touch unfocused window. This should force the pending key to get dropped.
5103 NotifyMotionArgs motionArgs =
5104 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5105 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5106 mDispatcher->notifyMotion(&motionArgs);
5107
5108 // We do not consume the motion right away, because that would require dispatcher to first
5109 // process (== drop) the key event, and by that time, ANR will be raised.
5110 // Set the focused window first.
5111 mFocusedWindow->setFocusable(true);
5112 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5113 setFocusedWindow(mFocusedWindow);
5114 mFocusedWindow->consumeFocusEvent(true);
5115 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5116 // to another application. This could be a bug / behaviour in the policy.
5117
5118 mUnfocusedWindow->consumeMotionDown();
5119
5120 ASSERT_TRUE(mDispatcher->waitForIdle());
5121 // Should not ANR because we actually have a focused window. It was just added too slowly.
5122 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5123}
5124
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005125// These tests ensure we cannot send touch events to a window that's positioned behind a window
5126// that has feature NO_INPUT_CHANNEL.
5127// Layout:
5128// Top (closest to user)
5129// mNoInputWindow (above all windows)
5130// mBottomWindow
5131// Bottom (furthest from user)
5132class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5133 virtual void SetUp() override {
5134 InputDispatcherTest::SetUp();
5135
5136 mApplication = std::make_shared<FakeApplicationHandle>();
5137 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5138 "Window without input channel", ADISPLAY_ID_DEFAULT,
5139 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5140
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005141 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005142 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5143 // It's perfectly valid for this window to not have an associated input channel
5144
5145 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5146 ADISPLAY_ID_DEFAULT);
5147 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5148
5149 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5150 }
5151
5152protected:
5153 std::shared_ptr<FakeApplicationHandle> mApplication;
5154 sp<FakeWindowHandle> mNoInputWindow;
5155 sp<FakeWindowHandle> mBottomWindow;
5156};
5157
5158TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5159 PointF touchedPoint = {10, 10};
5160
5161 NotifyMotionArgs motionArgs =
5162 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5163 ADISPLAY_ID_DEFAULT, {touchedPoint});
5164 mDispatcher->notifyMotion(&motionArgs);
5165
5166 mNoInputWindow->assertNoEvents();
5167 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5168 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5169 // and therefore should prevent mBottomWindow from receiving touches
5170 mBottomWindow->assertNoEvents();
5171}
5172
5173/**
5174 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5175 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5176 */
5177TEST_F(InputDispatcherMultiWindowOcclusionTests,
5178 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5179 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5180 "Window with input channel and NO_INPUT_CHANNEL",
5181 ADISPLAY_ID_DEFAULT);
5182
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005183 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005184 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5185 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5186
5187 PointF touchedPoint = {10, 10};
5188
5189 NotifyMotionArgs motionArgs =
5190 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5191 ADISPLAY_ID_DEFAULT, {touchedPoint});
5192 mDispatcher->notifyMotion(&motionArgs);
5193
5194 mNoInputWindow->assertNoEvents();
5195 mBottomWindow->assertNoEvents();
5196}
5197
Vishnu Nair958da932020-08-21 17:12:37 -07005198class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5199protected:
5200 std::shared_ptr<FakeApplicationHandle> mApp;
5201 sp<FakeWindowHandle> mWindow;
5202 sp<FakeWindowHandle> mMirror;
5203
5204 virtual void SetUp() override {
5205 InputDispatcherTest::SetUp();
5206 mApp = std::make_shared<FakeApplicationHandle>();
5207 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5208 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5209 mWindow->getToken());
5210 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5211 mWindow->setFocusable(true);
5212 mMirror->setFocusable(true);
5213 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5214 }
5215};
5216
5217TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5218 // Request focus on a mirrored window
5219 setFocusedWindow(mMirror);
5220
5221 // window gets focused
5222 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005223 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5224 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005225 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5226}
5227
5228// A focused & mirrored window remains focused only if the window and its mirror are both
5229// focusable.
5230TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5231 setFocusedWindow(mMirror);
5232
5233 // window gets focused
5234 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005235 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5236 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005237 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005238 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5239 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005240 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5241
5242 mMirror->setFocusable(false);
5243 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5244
5245 // window loses focus since one of the windows associated with the token in not focusable
5246 mWindow->consumeFocusEvent(false);
5247
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005248 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5249 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005250 mWindow->assertNoEvents();
5251}
5252
5253// A focused & mirrored window remains focused until the window and its mirror both become
5254// invisible.
5255TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5256 setFocusedWindow(mMirror);
5257
5258 // window gets focused
5259 mWindow->consumeFocusEvent(true);
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 mMirror->setVisible(false);
5268 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5269
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005270 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5271 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005272 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005273 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5274 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005275 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5276
5277 mWindow->setVisible(false);
5278 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5279
5280 // window loses focus only after all windows associated with the token become invisible.
5281 mWindow->consumeFocusEvent(false);
5282
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005283 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5284 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005285 mWindow->assertNoEvents();
5286}
5287
5288// A focused & mirrored window remains focused until both windows are removed.
5289TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5290 setFocusedWindow(mMirror);
5291
5292 // window gets focused
5293 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005294 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5295 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005296 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005297 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5298 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005299 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5300
5301 // single window is removed but the window token remains focused
5302 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5303
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005304 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5305 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005306 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005307 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5308 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005309 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5310
5311 // Both windows are removed
5312 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5313 mWindow->consumeFocusEvent(false);
5314
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005315 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5316 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005317 mWindow->assertNoEvents();
5318}
5319
5320// Focus request can be pending until one window becomes visible.
5321TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5322 // Request focus on an invisible mirror.
5323 mWindow->setVisible(false);
5324 mMirror->setVisible(false);
5325 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5326 setFocusedWindow(mMirror);
5327
5328 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005329 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005330 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005331 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005332
5333 mMirror->setVisible(true);
5334 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5335
5336 // window gets focused
5337 mWindow->consumeFocusEvent(true);
5338 // window gets the pending key event
5339 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5340}
Prabir Pradhan99987712020-11-10 18:43:05 -08005341
5342class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5343protected:
5344 std::shared_ptr<FakeApplicationHandle> mApp;
5345 sp<FakeWindowHandle> mWindow;
5346 sp<FakeWindowHandle> mSecondWindow;
5347
5348 void SetUp() override {
5349 InputDispatcherTest::SetUp();
5350 mApp = std::make_shared<FakeApplicationHandle>();
5351 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5352 mWindow->setFocusable(true);
5353 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5354 mSecondWindow->setFocusable(true);
5355
5356 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5357 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5358
5359 setFocusedWindow(mWindow);
5360 mWindow->consumeFocusEvent(true);
5361 }
5362
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005363 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5364 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005365 mDispatcher->notifyPointerCaptureChanged(&args);
5366 }
5367
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005368 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5369 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005370 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005371 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5372 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005373 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005374 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005375 }
5376};
5377
5378TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5379 // Ensure that capture cannot be obtained for unfocused windows.
5380 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5381 mFakePolicy->assertSetPointerCaptureNotCalled();
5382 mSecondWindow->assertNoEvents();
5383
5384 // Ensure that capture can be enabled from the focus window.
5385 requestAndVerifyPointerCapture(mWindow, true);
5386
5387 // Ensure that capture cannot be disabled from a window that does not have capture.
5388 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5389 mFakePolicy->assertSetPointerCaptureNotCalled();
5390
5391 // Ensure that capture can be disabled from the window with capture.
5392 requestAndVerifyPointerCapture(mWindow, false);
5393}
5394
5395TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005396 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005397
5398 setFocusedWindow(mSecondWindow);
5399
5400 // Ensure that the capture disabled event was sent first.
5401 mWindow->consumeCaptureEvent(false);
5402 mWindow->consumeFocusEvent(false);
5403 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005404 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005405
5406 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005407 notifyPointerCaptureChanged({});
5408 notifyPointerCaptureChanged(request);
5409 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005410 mWindow->assertNoEvents();
5411 mSecondWindow->assertNoEvents();
5412 mFakePolicy->assertSetPointerCaptureNotCalled();
5413}
5414
5415TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005416 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005417
5418 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005419 notifyPointerCaptureChanged({});
5420 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005421
5422 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005423 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005424 mWindow->consumeCaptureEvent(false);
5425 mWindow->assertNoEvents();
5426}
5427
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005428TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5429 requestAndVerifyPointerCapture(mWindow, true);
5430
5431 // The first window loses focus.
5432 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005433 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005434 mWindow->consumeCaptureEvent(false);
5435
5436 // Request Pointer Capture from the second window before the notification from InputReader
5437 // arrives.
5438 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005439 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005440
5441 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005442 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005443
5444 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005445 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005446
5447 mSecondWindow->consumeFocusEvent(true);
5448 mSecondWindow->consumeCaptureEvent(true);
5449}
5450
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005451TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5452 // App repeatedly enables and disables capture.
5453 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5454 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5455 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5456 mFakePolicy->assertSetPointerCaptureCalled(false);
5457 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5458 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5459
5460 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5461 // first request is now stale, this should do nothing.
5462 notifyPointerCaptureChanged(firstRequest);
5463 mWindow->assertNoEvents();
5464
5465 // InputReader notifies that the second request was enabled.
5466 notifyPointerCaptureChanged(secondRequest);
5467 mWindow->consumeCaptureEvent(true);
5468}
5469
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005470class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5471protected:
5472 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005473
5474 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5475 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5476
5477 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5478 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5479
5480 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5481 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5482 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5483 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5484 MAXIMUM_OBSCURING_OPACITY);
5485
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005486 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005487 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005488 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005489
5490 sp<FakeWindowHandle> mTouchWindow;
5491
5492 virtual void SetUp() override {
5493 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005494 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005495 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5496 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5497 }
5498
5499 virtual void TearDown() override {
5500 InputDispatcherTest::TearDown();
5501 mTouchWindow.clear();
5502 }
5503
chaviw3277faf2021-05-19 16:45:23 -05005504 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5505 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005506 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005507 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005508 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005509 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005510 return window;
5511 }
5512
5513 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5514 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5515 sp<FakeWindowHandle> window =
5516 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5517 // Generate an arbitrary PID based on the UID
5518 window->setOwnerInfo(1777 + (uid % 10000), uid);
5519 return window;
5520 }
5521
5522 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5523 NotifyMotionArgs args =
5524 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5525 ADISPLAY_ID_DEFAULT, points);
5526 mDispatcher->notifyMotion(&args);
5527 }
5528};
5529
5530TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005531 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005532 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005533 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005534
5535 touch();
5536
5537 mTouchWindow->assertNoEvents();
5538}
5539
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005540TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005541 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5542 const sp<FakeWindowHandle>& w =
5543 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5544 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5545
5546 touch();
5547
5548 mTouchWindow->assertNoEvents();
5549}
5550
5551TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005552 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5553 const sp<FakeWindowHandle>& w =
5554 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5555 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5556
5557 touch();
5558
5559 w->assertNoEvents();
5560}
5561
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005562TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005563 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5564 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005565
5566 touch();
5567
5568 mTouchWindow->consumeAnyMotionDown();
5569}
5570
5571TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005572 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005573 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005574 w->setFrame(Rect(0, 0, 50, 50));
5575 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005576
5577 touch({PointF{100, 100}});
5578
5579 mTouchWindow->consumeAnyMotionDown();
5580}
5581
5582TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005583 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005584 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005585 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5586
5587 touch();
5588
5589 mTouchWindow->consumeAnyMotionDown();
5590}
5591
5592TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5593 const sp<FakeWindowHandle>& w =
5594 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5595 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005596
5597 touch();
5598
5599 mTouchWindow->consumeAnyMotionDown();
5600}
5601
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005602TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5603 const sp<FakeWindowHandle>& w =
5604 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5605 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5606
5607 touch();
5608
5609 w->assertNoEvents();
5610}
5611
5612/**
5613 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5614 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5615 * window, the occluding window will still receive ACTION_OUTSIDE event.
5616 */
5617TEST_F(InputDispatcherUntrustedTouchesTest,
5618 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5619 const sp<FakeWindowHandle>& w =
5620 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005621 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005622 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5623
5624 touch();
5625
5626 w->consumeMotionOutside();
5627}
5628
5629TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5630 const sp<FakeWindowHandle>& w =
5631 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005632 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005633 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5634
5635 touch();
5636
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005637 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005638}
5639
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005640TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005641 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005642 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5643 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005644 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5645
5646 touch();
5647
5648 mTouchWindow->consumeAnyMotionDown();
5649}
5650
5651TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5652 const sp<FakeWindowHandle>& w =
5653 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5654 MAXIMUM_OBSCURING_OPACITY);
5655 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005656
5657 touch();
5658
5659 mTouchWindow->consumeAnyMotionDown();
5660}
5661
5662TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005663 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005664 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5665 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005666 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5667
5668 touch();
5669
5670 mTouchWindow->assertNoEvents();
5671}
5672
5673TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5674 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5675 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005676 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5677 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005678 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005679 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5680 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005681 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5682
5683 touch();
5684
5685 mTouchWindow->assertNoEvents();
5686}
5687
5688TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5689 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5690 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005691 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5692 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005693 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005694 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5695 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005696 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5697
5698 touch();
5699
5700 mTouchWindow->consumeAnyMotionDown();
5701}
5702
5703TEST_F(InputDispatcherUntrustedTouchesTest,
5704 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5705 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005706 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5707 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005708 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005709 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5710 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005711 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5712
5713 touch();
5714
5715 mTouchWindow->consumeAnyMotionDown();
5716}
5717
5718TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5719 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005720 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5721 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005722 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005723 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5724 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005725 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005726
5727 touch();
5728
5729 mTouchWindow->assertNoEvents();
5730}
5731
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005732TEST_F(InputDispatcherUntrustedTouchesTest,
5733 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5734 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005735 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5736 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005737 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005738 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5739 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005740 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5741
5742 touch();
5743
5744 mTouchWindow->assertNoEvents();
5745}
5746
5747TEST_F(InputDispatcherUntrustedTouchesTest,
5748 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5749 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005750 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5751 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005752 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005753 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5754 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005755 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5756
5757 touch();
5758
5759 mTouchWindow->consumeAnyMotionDown();
5760}
5761
5762TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5763 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005764 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5765 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005766 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5767
5768 touch();
5769
5770 mTouchWindow->consumeAnyMotionDown();
5771}
5772
5773TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5774 const sp<FakeWindowHandle>& w =
5775 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5776 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5777
5778 touch();
5779
5780 mTouchWindow->consumeAnyMotionDown();
5781}
5782
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005783TEST_F(InputDispatcherUntrustedTouchesTest,
5784 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5785 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5786 const sp<FakeWindowHandle>& w =
5787 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5788 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5789
5790 touch();
5791
5792 mTouchWindow->assertNoEvents();
5793}
5794
5795TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5796 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5797 const sp<FakeWindowHandle>& w =
5798 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5799 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5800
5801 touch();
5802
5803 mTouchWindow->consumeAnyMotionDown();
5804}
5805
5806TEST_F(InputDispatcherUntrustedTouchesTest,
5807 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5808 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5809 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005810 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5811 OPACITY_ABOVE_THRESHOLD);
5812 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5813
5814 touch();
5815
5816 mTouchWindow->consumeAnyMotionDown();
5817}
5818
5819TEST_F(InputDispatcherUntrustedTouchesTest,
5820 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5821 const sp<FakeWindowHandle>& w1 =
5822 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5823 OPACITY_BELOW_THRESHOLD);
5824 const sp<FakeWindowHandle>& w2 =
5825 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5826 OPACITY_BELOW_THRESHOLD);
5827 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5828
5829 touch();
5830
5831 mTouchWindow->assertNoEvents();
5832}
5833
5834/**
5835 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5836 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5837 * (which alone would result in allowing touches) does not affect the blocking behavior.
5838 */
5839TEST_F(InputDispatcherUntrustedTouchesTest,
5840 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5841 const sp<FakeWindowHandle>& wB =
5842 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5843 OPACITY_BELOW_THRESHOLD);
5844 const sp<FakeWindowHandle>& wC =
5845 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5846 OPACITY_BELOW_THRESHOLD);
5847 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5848
5849 touch();
5850
5851 mTouchWindow->assertNoEvents();
5852}
5853
5854/**
5855 * This test is testing that a window from a different UID but with same application token doesn't
5856 * block the touch. Apps can share the application token for close UI collaboration for example.
5857 */
5858TEST_F(InputDispatcherUntrustedTouchesTest,
5859 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5860 const sp<FakeWindowHandle>& w =
5861 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5862 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005863 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5864
5865 touch();
5866
5867 mTouchWindow->consumeAnyMotionDown();
5868}
5869
arthurhungb89ccb02020-12-30 16:19:01 +08005870class InputDispatcherDragTests : public InputDispatcherTest {
5871protected:
5872 std::shared_ptr<FakeApplicationHandle> mApp;
5873 sp<FakeWindowHandle> mWindow;
5874 sp<FakeWindowHandle> mSecondWindow;
5875 sp<FakeWindowHandle> mDragWindow;
5876
5877 void SetUp() override {
5878 InputDispatcherTest::SetUp();
5879 mApp = std::make_shared<FakeApplicationHandle>();
5880 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5881 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005882
5883 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5884 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005885
5886 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5887 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5888 }
5889
5890 // Start performing drag, we will create a drag window and transfer touch to it.
5891 void performDrag() {
5892 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5893 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5894 {50, 50}))
5895 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5896
5897 // Window should receive motion event.
5898 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5899
5900 // The drag window covers the entire display
5901 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5902 mDispatcher->setInputWindows(
5903 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5904
5905 // Transfer touch focus to the drag window
5906 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5907 true /* isDragDrop */);
5908 mWindow->consumeMotionCancel();
5909 mDragWindow->consumeMotionDown();
5910 }
arthurhung6d4bed92021-03-17 11:59:33 +08005911
5912 // Start performing drag, we will create a drag window and transfer touch to it.
5913 void performStylusDrag() {
5914 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5915 injectMotionEvent(mDispatcher,
5916 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5917 AINPUT_SOURCE_STYLUS)
5918 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5919 .pointer(PointerBuilder(0,
5920 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5921 .x(50)
5922 .y(50))
5923 .build()));
5924 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5925
5926 // The drag window covers the entire display
5927 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5928 mDispatcher->setInputWindows(
5929 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5930
5931 // Transfer touch focus to the drag window
5932 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5933 true /* isDragDrop */);
5934 mWindow->consumeMotionCancel();
5935 mDragWindow->consumeMotionDown();
5936 }
arthurhungb89ccb02020-12-30 16:19:01 +08005937};
5938
5939TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5940 performDrag();
5941
5942 // Move on window.
5943 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5944 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5945 ADISPLAY_ID_DEFAULT, {50, 50}))
5946 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5947 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5948 mWindow->consumeDragEvent(false, 50, 50);
5949 mSecondWindow->assertNoEvents();
5950
5951 // Move to another window.
5952 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5953 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5954 ADISPLAY_ID_DEFAULT, {150, 50}))
5955 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5956 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5957 mWindow->consumeDragEvent(true, 150, 50);
5958 mSecondWindow->consumeDragEvent(false, 50, 50);
5959
5960 // Move back to original window.
5961 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5962 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5963 ADISPLAY_ID_DEFAULT, {50, 50}))
5964 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5965 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5966 mWindow->consumeDragEvent(false, 50, 50);
5967 mSecondWindow->consumeDragEvent(true, -50, 50);
5968
5969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5970 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5971 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5972 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5973 mWindow->assertNoEvents();
5974 mSecondWindow->assertNoEvents();
5975}
5976
arthurhungf452d0b2021-01-06 00:19:52 +08005977TEST_F(InputDispatcherDragTests, DragAndDrop) {
5978 performDrag();
5979
5980 // Move on window.
5981 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5982 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5983 ADISPLAY_ID_DEFAULT, {50, 50}))
5984 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5985 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5986 mWindow->consumeDragEvent(false, 50, 50);
5987 mSecondWindow->assertNoEvents();
5988
5989 // Move to another window.
5990 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5991 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5992 ADISPLAY_ID_DEFAULT, {150, 50}))
5993 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5994 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5995 mWindow->consumeDragEvent(true, 150, 50);
5996 mSecondWindow->consumeDragEvent(false, 50, 50);
5997
5998 // drop to another window.
5999 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6000 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6001 {150, 50}))
6002 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6003 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6004 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6005 mWindow->assertNoEvents();
6006 mSecondWindow->assertNoEvents();
6007}
6008
arthurhung6d4bed92021-03-17 11:59:33 +08006009TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6010 performStylusDrag();
6011
6012 // Move on window and keep button pressed.
6013 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6014 injectMotionEvent(mDispatcher,
6015 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6016 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6017 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6018 .x(50)
6019 .y(50))
6020 .build()))
6021 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6022 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6023 mWindow->consumeDragEvent(false, 50, 50);
6024 mSecondWindow->assertNoEvents();
6025
6026 // Move to another window and release button, expect to drop item.
6027 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6028 injectMotionEvent(mDispatcher,
6029 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6030 .buttonState(0)
6031 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6032 .x(150)
6033 .y(50))
6034 .build()))
6035 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6036 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6037 mWindow->assertNoEvents();
6038 mSecondWindow->assertNoEvents();
6039 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6040
6041 // nothing to the window.
6042 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6043 injectMotionEvent(mDispatcher,
6044 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6045 .buttonState(0)
6046 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6047 .x(150)
6048 .y(50))
6049 .build()))
6050 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6051 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6052 mWindow->assertNoEvents();
6053 mSecondWindow->assertNoEvents();
6054}
6055
Arthur Hung6d0571e2021-04-09 20:18:16 +08006056TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6057 performDrag();
6058
6059 // Set second window invisible.
6060 mSecondWindow->setVisible(false);
6061 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6062
6063 // Move on window.
6064 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6065 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6066 ADISPLAY_ID_DEFAULT, {50, 50}))
6067 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6068 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6069 mWindow->consumeDragEvent(false, 50, 50);
6070 mSecondWindow->assertNoEvents();
6071
6072 // Move to another window.
6073 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6074 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6075 ADISPLAY_ID_DEFAULT, {150, 50}))
6076 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6077 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6078 mWindow->consumeDragEvent(true, 150, 50);
6079 mSecondWindow->assertNoEvents();
6080
6081 // drop to another window.
6082 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6083 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6084 {150, 50}))
6085 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6086 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6087 mFakePolicy->assertDropTargetEquals(nullptr);
6088 mWindow->assertNoEvents();
6089 mSecondWindow->assertNoEvents();
6090}
6091
Vishnu Nair062a8672021-09-03 16:07:44 -07006092class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6093
6094TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6095 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6096 sp<FakeWindowHandle> window =
6097 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006098 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006099 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6100 window->setFocusable(true);
6101 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6102 setFocusedWindow(window);
6103 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6104
6105 // With the flag set, window should not get any input
6106 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6107 mDispatcher->notifyKey(&keyArgs);
6108 window->assertNoEvents();
6109
6110 NotifyMotionArgs motionArgs =
6111 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6112 ADISPLAY_ID_DEFAULT);
6113 mDispatcher->notifyMotion(&motionArgs);
6114 window->assertNoEvents();
6115
6116 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006117 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006118 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6119
6120 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6121 mDispatcher->notifyKey(&keyArgs);
6122 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6123
6124 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6125 ADISPLAY_ID_DEFAULT);
6126 mDispatcher->notifyMotion(&motionArgs);
6127 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6128 window->assertNoEvents();
6129}
6130
6131TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6132 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6133 std::make_shared<FakeApplicationHandle>();
6134 sp<FakeWindowHandle> obscuringWindow =
6135 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6136 ADISPLAY_ID_DEFAULT);
6137 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6138 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006139 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006140 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6141 sp<FakeWindowHandle> window =
6142 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006143 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006144 window->setOwnerInfo(222, 222);
6145 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6146 window->setFocusable(true);
6147 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6148 setFocusedWindow(window);
6149 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6150
6151 // With the flag set, window should not get any input
6152 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6153 mDispatcher->notifyKey(&keyArgs);
6154 window->assertNoEvents();
6155
6156 NotifyMotionArgs motionArgs =
6157 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6158 ADISPLAY_ID_DEFAULT);
6159 mDispatcher->notifyMotion(&motionArgs);
6160 window->assertNoEvents();
6161
6162 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006163 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006164 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6165
6166 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6167 mDispatcher->notifyKey(&keyArgs);
6168 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6169
6170 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6171 ADISPLAY_ID_DEFAULT);
6172 mDispatcher->notifyMotion(&motionArgs);
6173 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6174 window->assertNoEvents();
6175}
6176
6177TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6178 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6179 std::make_shared<FakeApplicationHandle>();
6180 sp<FakeWindowHandle> obscuringWindow =
6181 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6182 ADISPLAY_ID_DEFAULT);
6183 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6184 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006185 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006186 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6187 sp<FakeWindowHandle> window =
6188 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006189 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006190 window->setOwnerInfo(222, 222);
6191 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6192 window->setFocusable(true);
6193 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6194 setFocusedWindow(window);
6195 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6196
6197 // With the flag set, window should not get any input
6198 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6199 mDispatcher->notifyKey(&keyArgs);
6200 window->assertNoEvents();
6201
6202 NotifyMotionArgs motionArgs =
6203 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6204 ADISPLAY_ID_DEFAULT);
6205 mDispatcher->notifyMotion(&motionArgs);
6206 window->assertNoEvents();
6207
6208 // When the window is no longer obscured because it went on top, it should get input
6209 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6210
6211 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6212 mDispatcher->notifyKey(&keyArgs);
6213 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6214
6215 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6216 ADISPLAY_ID_DEFAULT);
6217 mDispatcher->notifyMotion(&motionArgs);
6218 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6219 window->assertNoEvents();
6220}
6221
Antonio Kantekf16f2832021-09-28 04:39:20 +00006222class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6223protected:
6224 std::shared_ptr<FakeApplicationHandle> mApp;
6225 sp<FakeWindowHandle> mWindow;
6226 sp<FakeWindowHandle> mSecondWindow;
6227
6228 void SetUp() override {
6229 InputDispatcherTest::SetUp();
6230
6231 mApp = std::make_shared<FakeApplicationHandle>();
6232 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6233 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006234 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006235 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6236 mSecondWindow->setFocusable(true);
6237
6238 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6239 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006240 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006241
6242 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
6243 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, INJECTOR_PID,
6244 INJECTOR_UID, /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006245 }
6246
Antonio Kantekea47acb2021-12-23 12:41:25 -08006247 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006248 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006249 mWindow->consumeTouchModeEvent(inTouchMode);
6250 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6251 }
6252};
6253
Antonio Kantek26defcf2022-02-08 01:12:27 +00006254TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006255 const WindowInfo& windowInfo = *mWindow->getInfo();
6256 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6257 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006258}
6259
Antonio Kantek26defcf2022-02-08 01:12:27 +00006260TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6261 const WindowInfo& windowInfo = *mWindow->getInfo();
6262 int32_t ownerPid = windowInfo.ownerPid;
6263 int32_t ownerUid = windowInfo.ownerUid;
6264 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6265 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6266 ownerUid, /* hasPermission */ false));
6267 mWindow->assertNoEvents();
6268 mSecondWindow->assertNoEvents();
6269}
6270
6271TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6272 const WindowInfo& windowInfo = *mWindow->getInfo();
6273 int32_t ownerPid = windowInfo.ownerPid;
6274 int32_t ownerUid = windowInfo.ownerUid;
6275 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6276 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6277 /* hasPermission */ true);
6278}
6279
Antonio Kantekf16f2832021-09-28 04:39:20 +00006280TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006281 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006282 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6283 windowInfo.ownerPid, windowInfo.ownerUid,
6284 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006285 mWindow->assertNoEvents();
6286 mSecondWindow->assertNoEvents();
6287}
6288
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006289class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6290public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006291 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006292 std::shared_ptr<FakeApplicationHandle> application =
6293 std::make_shared<FakeApplicationHandle>();
6294 std::string name = "Fake Spy ";
6295 name += std::to_string(mSpyCount++);
6296 sp<FakeWindowHandle> spy =
6297 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006298 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006299 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006300 return spy;
6301 }
6302
6303 sp<FakeWindowHandle> createForeground() {
6304 std::shared_ptr<FakeApplicationHandle> application =
6305 std::make_shared<FakeApplicationHandle>();
6306 sp<FakeWindowHandle> window =
6307 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006308 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006309 return window;
6310 }
6311
6312private:
6313 int mSpyCount{0};
6314};
6315
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006316using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006317/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006318 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6319 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006320TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6321 ScopedSilentDeath _silentDeath;
6322
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006323 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006324 spy->setTrustedOverlay(false);
6325 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6326 ".* not a trusted overlay");
6327}
6328
6329/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006330 * Input injection into a display with a spy window but no foreground windows should succeed.
6331 */
6332TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006333 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006334 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6335
6336 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6337 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6338 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6339 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6340}
6341
6342/**
6343 * Verify the order in which different input windows receive events. The touched foreground window
6344 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6345 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6346 * receive events before ones belows it.
6347 *
6348 * Here, we set up a scenario with four windows in the following Z order from the top:
6349 * spy1, spy2, window, spy3.
6350 * We then inject an event and verify that the foreground "window" receives it first, followed by
6351 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6352 * window.
6353 */
6354TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6355 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006356 auto spy1 = createSpy();
6357 auto spy2 = createSpy();
6358 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006359 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6360 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6361 const size_t numChannels = channels.size();
6362
Michael Wright8e9a8562022-02-09 13:44:29 +00006363 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006364 if (!epollFd.ok()) {
6365 FAIL() << "Failed to create epoll fd";
6366 }
6367
6368 for (size_t i = 0; i < numChannels; i++) {
6369 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6370 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6371 FAIL() << "Failed to add fd to epoll";
6372 }
6373 }
6374
6375 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6376 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6377 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6378
6379 std::vector<size_t> eventOrder;
6380 std::vector<struct epoll_event> events(numChannels);
6381 for (;;) {
6382 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6383 (100ms).count());
6384 if (nFds < 0) {
6385 FAIL() << "Failed to call epoll_wait";
6386 }
6387 if (nFds == 0) {
6388 break; // epoll_wait timed out
6389 }
6390 for (int i = 0; i < nFds; i++) {
6391 ASSERT_EQ(EPOLLIN, events[i].events);
6392 eventOrder.push_back(events[i].data.u64);
6393 channels[i]->consumeMotionDown();
6394 }
6395 }
6396
6397 // Verify the order in which the events were received.
6398 EXPECT_EQ(3u, eventOrder.size());
6399 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6400 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6401 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6402}
6403
6404/**
6405 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6406 */
6407TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6408 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006409 auto spy = createSpy();
6410 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006411 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6412
6413 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6414 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6415 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6416 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6417 spy->assertNoEvents();
6418}
6419
6420/**
6421 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6422 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6423 * to the window.
6424 */
6425TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6426 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006427 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006428 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6429 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6430
6431 // Inject an event outside the spy window's touchable region.
6432 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6433 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6434 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6435 window->consumeMotionDown();
6436 spy->assertNoEvents();
6437 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6438 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6439 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6440 window->consumeMotionUp();
6441 spy->assertNoEvents();
6442
6443 // Inject an event inside the spy window's touchable region.
6444 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6445 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6446 {5, 10}))
6447 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6448 window->consumeMotionDown();
6449 spy->consumeMotionDown();
6450}
6451
6452/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006453 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006454 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006455 */
6456TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6457 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006458 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006459 auto spy = createSpy();
6460 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006461 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006462 spy->setFrame(Rect{0, 0, 20, 20});
6463 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6464
6465 // Inject an event outside the spy window's frame and touchable region.
6466 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006467 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6468 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006469 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6470 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006471 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006472}
6473
6474/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006475 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6476 * any other windows - including other spy windows - will also be cancelled.
6477 */
6478TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6479 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006480 auto spy1 = createSpy();
6481 auto spy2 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006482 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6483
6484 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6485 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6486 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6487 window->consumeMotionDown();
6488 spy1->consumeMotionDown();
6489 spy2->consumeMotionDown();
6490
6491 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006492 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006493 spy2->assertNoEvents();
6494 spy1->consumeMotionCancel();
6495 window->consumeMotionCancel();
6496
6497 // The rest of the gesture should only be sent to the second spy window.
6498 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6499 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6500 ADISPLAY_ID_DEFAULT))
6501 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6502 spy2->consumeMotionMove();
6503 spy1->assertNoEvents();
6504 window->assertNoEvents();
6505}
6506
6507/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006508 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
6509 * in the middle of the gesture.
6510 */
6511TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
6512 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006513 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006514 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6515
6516 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6517 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6518 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6519 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6520 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6521
6522 window->releaseChannel();
6523
6524 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6525
6526 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6527 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6528 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6529 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6530}
6531
6532/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006533 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
6534 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006535 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006536TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006537 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006538 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006539
6540 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6541
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006542 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006543 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6544 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6545 {100, 200}))
6546 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006547 spy->consumeMotionDown();
6548 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006549
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006550 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006551 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006552 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006553
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006554 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006555 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006556 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006557 .displayId(ADISPLAY_ID_DEFAULT)
6558 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6559 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6560 .x(100)
6561 .y(200))
6562 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6563 .build();
6564 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6565 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6566 InputEventInjectionSync::WAIT_FOR_RESULT))
6567 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6568
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006569 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6570
6571 // Third finger goes down outside all windows, so injection should fail.
6572 const MotionEvent thirdFingerDownEvent =
6573 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6574 (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6575 AINPUT_SOURCE_TOUCHSCREEN)
6576 .displayId(ADISPLAY_ID_DEFAULT)
6577 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6578 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6579 .x(100)
6580 .y(200))
6581 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6582 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
6583 .build();
6584 ASSERT_EQ(InputEventInjectionResult::FAILED,
6585 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
6586 InputEventInjectionSync::WAIT_FOR_RESULT))
6587 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6588
6589 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006590 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006591}
6592
6593/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006594 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6595 * pointers that are down within its bounds.
6596 */
6597TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6598 auto windowLeft = createForeground();
6599 windowLeft->setFrame({0, 0, 100, 200});
6600 auto windowRight = createForeground();
6601 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006602 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006603 spy->setFrame({0, 0, 200, 200});
6604 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6605
6606 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6607 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6608 {50, 50}))
6609 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6610 windowLeft->consumeMotionDown();
6611 spy->consumeMotionDown();
6612
6613 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006614 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006615 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6616 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6617 .pointer(
6618 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6619 .build();
6620 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6621 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6622 InputEventInjectionSync::WAIT_FOR_RESULT))
6623 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6624 windowRight->consumeMotionDown();
6625 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6626}
6627
6628/**
6629 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6630 * the spy should receive the second pointer with ACTION_DOWN.
6631 */
6632TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6633 auto window = createForeground();
6634 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006635 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006636 spyRight->setFrame({100, 0, 200, 200});
6637 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6638
6639 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6640 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6641 {50, 50}))
6642 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6643 window->consumeMotionDown();
6644 spyRight->assertNoEvents();
6645
6646 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006647 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006648 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6649 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6650 .pointer(
6651 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6652 .build();
6653 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6654 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6655 InputEventInjectionSync::WAIT_FOR_RESULT))
6656 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6657 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6658 spyRight->consumeMotionDown();
6659}
6660
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006661/**
6662 * The spy window should not be able to affect whether or not touches are split. Only the foreground
6663 * windows should be allowed to control split touch.
6664 */
6665TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006666 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006667 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006668 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006669 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006670
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006671 auto window = createForeground();
6672 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006673
6674 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6675
6676 // First finger down, no window touched.
6677 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6678 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6679 {100, 200}))
6680 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6681 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6682 window->assertNoEvents();
6683
6684 // Second finger down on window, the window should receive touch down.
6685 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006686 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006687 .displayId(ADISPLAY_ID_DEFAULT)
6688 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6689 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6690 .x(100)
6691 .y(200))
6692 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6693 .build();
6694 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6695 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6696 InputEventInjectionSync::WAIT_FOR_RESULT))
6697 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6698
6699 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6700 spy->consumeMotionPointerDown(1 /* pointerIndex */);
6701}
6702
6703/**
6704 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
6705 * do not receive key events.
6706 */
6707TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006708 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006709 spy->setFocusable(false);
6710
6711 auto window = createForeground();
6712 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6713 setFocusedWindow(window);
6714 window->consumeFocusEvent(true);
6715
6716 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6717 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6718 window->consumeKeyDown(ADISPLAY_ID_NONE);
6719
6720 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6721 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6722 window->consumeKeyUp(ADISPLAY_ID_NONE);
6723
6724 spy->assertNoEvents();
6725}
6726
Prabir Pradhand65552b2021-10-07 11:23:50 -07006727class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6728public:
6729 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6730 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6731 std::make_shared<FakeApplicationHandle>();
6732 sp<FakeWindowHandle> overlay =
6733 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6734 ADISPLAY_ID_DEFAULT);
6735 overlay->setFocusable(false);
6736 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006737 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006738 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006739 overlay->setTrustedOverlay(true);
6740
6741 std::shared_ptr<FakeApplicationHandle> application =
6742 std::make_shared<FakeApplicationHandle>();
6743 sp<FakeWindowHandle> window =
6744 new FakeWindowHandle(application, mDispatcher, "Application window",
6745 ADISPLAY_ID_DEFAULT);
6746 window->setFocusable(true);
6747 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006748
6749 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6750 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6751 setFocusedWindow(window);
6752 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6753 return {std::move(overlay), std::move(window)};
6754 }
6755
6756 void sendFingerEvent(int32_t action) {
6757 NotifyMotionArgs motionArgs =
6758 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6759 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6760 mDispatcher->notifyMotion(&motionArgs);
6761 }
6762
6763 void sendStylusEvent(int32_t action) {
6764 NotifyMotionArgs motionArgs =
6765 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6766 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6767 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6768 mDispatcher->notifyMotion(&motionArgs);
6769 }
6770};
6771
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006772using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
6773
6774TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
6775 ScopedSilentDeath _silentDeath;
6776
Prabir Pradhand65552b2021-10-07 11:23:50 -07006777 auto [overlay, window] = setupStylusOverlayScenario();
6778 overlay->setTrustedOverlay(false);
6779 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6780 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6781 ".* not a trusted overlay");
6782}
6783
6784TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6785 auto [overlay, window] = setupStylusOverlayScenario();
6786 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6787
6788 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6789 overlay->consumeMotionDown();
6790 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6791 overlay->consumeMotionUp();
6792
6793 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6794 window->consumeMotionDown();
6795 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6796 window->consumeMotionUp();
6797
6798 overlay->assertNoEvents();
6799 window->assertNoEvents();
6800}
6801
6802TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6803 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006804 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006805 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6806
6807 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6808 overlay->consumeMotionDown();
6809 window->consumeMotionDown();
6810 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6811 overlay->consumeMotionUp();
6812 window->consumeMotionUp();
6813
6814 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6815 window->consumeMotionDown();
6816 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6817 window->consumeMotionUp();
6818
6819 overlay->assertNoEvents();
6820 window->assertNoEvents();
6821}
6822
Garfield Tane84e6f92019-08-29 17:28:41 -07006823} // namespace android::inputdispatcher