blob: dbbc734b91053f6c561705e592754b2dc4dae7d5 [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 Pradhan76bdecb2022-01-31 11:14:15 -0800997 mInfo.inputConfig = WindowInfo::InputConfig::NONE;
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
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001041 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1042
chaviw3277faf2021-05-19 16:45:23 -05001043 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001044
Bernardo Rufino7393d172021-02-26 13:56:11 +00001045 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1046
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001047 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001048 mInfo.frameLeft = frame.left;
1049 mInfo.frameTop = frame.top;
1050 mInfo.frameRight = frame.right;
1051 mInfo.frameBottom = frame.bottom;
1052 mInfo.touchableRegion.clear();
1053 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001054
1055 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1056 ui::Transform translate;
1057 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1058 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001059 }
1060
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001061 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1062
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001063 void setIsWallpaper(bool isWallpaper) {
1064 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1065 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001066
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001067 void setDupTouchToWallpaper(bool hasWallpaper) {
1068 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1069 }
chaviwd1c23182019-12-20 18:44:56 -08001070
Prabir Pradhand65552b2021-10-07 11:23:50 -07001071 void setInputFeatures(Flags<WindowInfo::Feature> features) { mInfo.inputFeatures = features; }
1072
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001073 void setTrustedOverlay(bool trustedOverlay) {
1074 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1075 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001076
chaviw9eaa22c2020-07-01 16:21:27 -07001077 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1078 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1079 }
1080
1081 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001082
yunho.shinf4a80b82020-11-16 21:13:57 +09001083 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1084
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001085 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1086 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1087 expectedFlags);
1088 }
1089
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001090 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1091 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1092 }
1093
Svet Ganov5d3bc372020-01-26 23:11:07 -08001094 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001095 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001096 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1097 expectedFlags);
1098 }
1099
1100 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001101 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001102 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1103 expectedFlags);
1104 }
1105
1106 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001107 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001108 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1109 }
1110
1111 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1112 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001113 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1114 expectedFlags);
1115 }
1116
Svet Ganov5d3bc372020-01-26 23:11:07 -08001117 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001118 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1119 int32_t expectedFlags = 0) {
1120 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1121 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001122 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1123 }
1124
1125 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001126 int32_t expectedFlags = 0) {
1127 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1128 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001129 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1130 }
1131
1132 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001133 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001134 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1135 expectedFlags);
1136 }
1137
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001138 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1139 int32_t expectedFlags = 0) {
1140 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1141 expectedFlags);
1142 }
1143
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001144 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1145 int32_t expectedFlags = 0) {
1146 InputEvent* event = consume();
1147 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1148 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1149 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1150 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1151 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1152 }
1153
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001154 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1155 ASSERT_NE(mInputReceiver, nullptr)
1156 << "Cannot consume events from a window with no receiver";
1157 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1158 }
1159
Prabir Pradhan99987712020-11-10 18:43:05 -08001160 void consumeCaptureEvent(bool hasCapture) {
1161 ASSERT_NE(mInputReceiver, nullptr)
1162 << "Cannot consume events from a window with no receiver";
1163 mInputReceiver->consumeCaptureEvent(hasCapture);
1164 }
1165
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001166 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1167 std::optional<int32_t> expectedDisplayId,
1168 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001169 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1170 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1171 expectedFlags);
1172 }
1173
arthurhungb89ccb02020-12-30 16:19:01 +08001174 void consumeDragEvent(bool isExiting, float x, float y) {
1175 mInputReceiver->consumeDragEvent(isExiting, x, y);
1176 }
1177
Antonio Kantekf16f2832021-09-28 04:39:20 +00001178 void consumeTouchModeEvent(bool inTouchMode) {
1179 ASSERT_NE(mInputReceiver, nullptr)
1180 << "Cannot consume events from a window with no receiver";
1181 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1182 }
1183
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001184 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001185 if (mInputReceiver == nullptr) {
1186 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1187 return std::nullopt;
1188 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001189 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001190 }
1191
1192 void finishEvent(uint32_t sequenceNum) {
1193 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1194 mInputReceiver->finishEvent(sequenceNum);
1195 }
1196
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001197 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1198 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1199 mInputReceiver->sendTimeline(inputEventId, timeline);
1200 }
1201
chaviwaf87b3e2019-10-01 16:59:28 -07001202 InputEvent* consume() {
1203 if (mInputReceiver == nullptr) {
1204 return nullptr;
1205 }
1206 return mInputReceiver->consume();
1207 }
1208
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001209 MotionEvent* consumeMotion() {
1210 InputEvent* event = consume();
1211 if (event == nullptr) {
1212 ADD_FAILURE() << "Consume failed : no event";
1213 return nullptr;
1214 }
1215 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1216 ADD_FAILURE() << "Instead of motion event, got "
1217 << inputEventTypeToString(event->getType());
1218 return nullptr;
1219 }
1220 return static_cast<MotionEvent*>(event);
1221 }
1222
Arthur Hungb92218b2018-08-14 12:00:21 +08001223 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001224 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001225 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001226 return; // Can't receive events if the window does not have input channel
1227 }
1228 ASSERT_NE(nullptr, mInputReceiver)
1229 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001230 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001231 }
1232
chaviwaf87b3e2019-10-01 16:59:28 -07001233 sp<IBinder> getToken() { return mInfo.token; }
1234
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001235 const std::string& getName() { return mName; }
1236
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001237 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1238 mInfo.ownerPid = ownerPid;
1239 mInfo.ownerUid = ownerUid;
1240 }
1241
Prabir Pradhanedd96402022-02-15 01:46:16 -08001242 int32_t getPid() const { return mInfo.ownerPid; }
1243
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001244 void destroyReceiver() { mInputReceiver = nullptr; }
1245
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001246 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1247
chaviwd1c23182019-12-20 18:44:56 -08001248private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001249 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001250 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001251 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001252};
1253
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001254std::atomic<int32_t> FakeWindowHandle::sId{1};
1255
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001256static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001257 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001258 int32_t displayId = ADISPLAY_ID_NONE,
1259 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001260 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1261 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001262 KeyEvent event;
1263 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1264
1265 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001266 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001267 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1268 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001269
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001270 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1271 if (!allowKeyRepeat) {
1272 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1273 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001274 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001275 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001276 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001277}
1278
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001279static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001280 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001281 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1282}
1283
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001284// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1285// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1286// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001287static InputEventInjectionResult injectKeyDownNoRepeat(
1288 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001289 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1290 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1291 /* allowKeyRepeat */ false);
1292}
1293
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001294static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001295 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001296 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1297}
1298
Garfield Tandf26e862020-07-01 20:18:19 -07001299class PointerBuilder {
1300public:
1301 PointerBuilder(int32_t id, int32_t toolType) {
1302 mProperties.clear();
1303 mProperties.id = id;
1304 mProperties.toolType = toolType;
1305 mCoords.clear();
1306 }
1307
1308 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1309
1310 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1311
1312 PointerBuilder& axis(int32_t axis, float value) {
1313 mCoords.setAxisValue(axis, value);
1314 return *this;
1315 }
1316
1317 PointerProperties buildProperties() const { return mProperties; }
1318
1319 PointerCoords buildCoords() const { return mCoords; }
1320
1321private:
1322 PointerProperties mProperties;
1323 PointerCoords mCoords;
1324};
1325
1326class MotionEventBuilder {
1327public:
1328 MotionEventBuilder(int32_t action, int32_t source) {
1329 mAction = action;
1330 mSource = source;
1331 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1332 }
1333
1334 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1335 mEventTime = eventTime;
1336 return *this;
1337 }
1338
1339 MotionEventBuilder& displayId(int32_t displayId) {
1340 mDisplayId = displayId;
1341 return *this;
1342 }
1343
1344 MotionEventBuilder& actionButton(int32_t actionButton) {
1345 mActionButton = actionButton;
1346 return *this;
1347 }
1348
arthurhung6d4bed92021-03-17 11:59:33 +08001349 MotionEventBuilder& buttonState(int32_t buttonState) {
1350 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001351 return *this;
1352 }
1353
1354 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1355 mRawXCursorPosition = rawXCursorPosition;
1356 return *this;
1357 }
1358
1359 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1360 mRawYCursorPosition = rawYCursorPosition;
1361 return *this;
1362 }
1363
1364 MotionEventBuilder& pointer(PointerBuilder pointer) {
1365 mPointers.push_back(pointer);
1366 return *this;
1367 }
1368
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001369 MotionEventBuilder& addFlag(uint32_t flags) {
1370 mFlags |= flags;
1371 return *this;
1372 }
1373
Garfield Tandf26e862020-07-01 20:18:19 -07001374 MotionEvent build() {
1375 std::vector<PointerProperties> pointerProperties;
1376 std::vector<PointerCoords> pointerCoords;
1377 for (const PointerBuilder& pointer : mPointers) {
1378 pointerProperties.push_back(pointer.buildProperties());
1379 pointerCoords.push_back(pointer.buildCoords());
1380 }
1381
1382 // Set mouse cursor position for the most common cases to avoid boilerplate.
1383 if (mSource == AINPUT_SOURCE_MOUSE &&
1384 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1385 mPointers.size() == 1) {
1386 mRawXCursorPosition = pointerCoords[0].getX();
1387 mRawYCursorPosition = pointerCoords[0].getY();
1388 }
1389
1390 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001391 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001392 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001393 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001394 mButtonState, MotionClassification::NONE, identityTransform,
1395 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001396 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1397 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001398
1399 return event;
1400 }
1401
1402private:
1403 int32_t mAction;
1404 int32_t mSource;
1405 nsecs_t mEventTime;
1406 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1407 int32_t mActionButton{0};
1408 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001409 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001410 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1411 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1412
1413 std::vector<PointerBuilder> mPointers;
1414};
1415
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001416static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001417 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001418 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001419 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001420 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1421 injectionTimeout,
1422 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1423}
1424
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001425static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001426 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001427 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001428 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001429 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1430 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001431 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001432 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001433 MotionEvent event = MotionEventBuilder(action, source)
1434 .displayId(displayId)
1435 .eventTime(eventTime)
1436 .rawXCursorPosition(cursorPosition.x)
1437 .rawYCursorPosition(cursorPosition.y)
1438 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1439 .x(position.x)
1440 .y(position.y))
1441 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001442
1443 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001444 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001445}
1446
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001447static InputEventInjectionResult injectMotionDown(
1448 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1449 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001450 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001451}
1452
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001453static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001454 int32_t source, int32_t displayId,
1455 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001456 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001457}
1458
Jackal Guof9696682018-10-05 12:23:23 +08001459static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1460 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1461 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001462 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1463 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1464 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001465
1466 return args;
1467}
1468
chaviwd1c23182019-12-20 18:44:56 -08001469static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1470 const std::vector<PointF>& points) {
1471 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001472 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1473 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1474 }
1475
chaviwd1c23182019-12-20 18:44:56 -08001476 PointerProperties pointerProperties[pointerCount];
1477 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001478
chaviwd1c23182019-12-20 18:44:56 -08001479 for (size_t i = 0; i < pointerCount; i++) {
1480 pointerProperties[i].clear();
1481 pointerProperties[i].id = i;
1482 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001483
chaviwd1c23182019-12-20 18:44:56 -08001484 pointerCoords[i].clear();
1485 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1486 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1487 }
Jackal Guof9696682018-10-05 12:23:23 +08001488
1489 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1490 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001491 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001492 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1493 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001494 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1495 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001496 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1497 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001498
1499 return args;
1500}
1501
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001502static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1503 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1504}
1505
chaviwd1c23182019-12-20 18:44:56 -08001506static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1507 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1508}
1509
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001510static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1511 const PointerCaptureRequest& request) {
1512 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001513}
1514
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001515/**
1516 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1517 * broken channel.
1518 */
1519TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1520 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1521 sp<FakeWindowHandle> window =
1522 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1523 ADISPLAY_ID_DEFAULT);
1524
1525 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1526
1527 // Window closes its channel, but the window remains.
1528 window->destroyReceiver();
1529 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1530}
1531
Arthur Hungb92218b2018-08-14 12:00:21 +08001532TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001533 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001534 sp<FakeWindowHandle> window =
1535 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001536
Arthur Hung72d8dc32020-03-28 00:48:39 +00001537 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001538 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1539 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1540 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001541
1542 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001543 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001544}
1545
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001546TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1547 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1548 sp<FakeWindowHandle> window =
1549 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1550
1551 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1552 // Inject a MotionEvent to an unknown display.
1553 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1554 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1555 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1556
1557 // Window should receive motion event.
1558 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1559}
1560
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001561/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001562 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001563 * This test serves as a sanity check for the next test, where setInputWindows is
1564 * called twice.
1565 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001566TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001567 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001568 sp<FakeWindowHandle> window =
1569 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1570 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001571
1572 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001573 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001574 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1575 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001576 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001577
1578 // Window should receive motion event.
1579 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1580}
1581
1582/**
1583 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001584 */
1585TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001586 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001587 sp<FakeWindowHandle> window =
1588 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1589 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001590
1591 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1592 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001593 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001594 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1595 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001596 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001597
1598 // Window should receive motion event.
1599 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1600}
1601
Arthur Hungb92218b2018-08-14 12:00:21 +08001602// The foreground window should receive the first touch down event.
1603TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001604 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001605 sp<FakeWindowHandle> windowTop =
1606 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1607 sp<FakeWindowHandle> windowSecond =
1608 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001609
Arthur Hung72d8dc32020-03-28 00:48:39 +00001610 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001611 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1612 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1613 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001614
1615 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001616 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001617 windowSecond->assertNoEvents();
1618}
1619
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001620/**
1621 * Two windows: A top window, and a wallpaper behind the window.
1622 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1623 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001624 * 1. foregroundWindow <-- dup touch to wallpaper
1625 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001626 */
1627TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1628 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1629 sp<FakeWindowHandle> foregroundWindow =
1630 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001631 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001632 sp<FakeWindowHandle> wallpaperWindow =
1633 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001634 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001635 constexpr int expectedWallpaperFlags =
1636 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1637
1638 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1639 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1640 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1641 {100, 200}))
1642 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1643
1644 // Both foreground window and its wallpaper should receive the touch down
1645 foregroundWindow->consumeMotionDown();
1646 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1647
1648 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1649 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1650 ADISPLAY_ID_DEFAULT, {110, 200}))
1651 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1652
1653 foregroundWindow->consumeMotionMove();
1654 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1655
1656 // Now the foreground window goes away, but the wallpaper stays
1657 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1658 foregroundWindow->consumeMotionCancel();
1659 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1660 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1661}
1662
1663/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001664 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1665 * with the following differences:
1666 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1667 * clean up the connection.
1668 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1669 * Ensure that there's no crash in the dispatcher.
1670 */
1671TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1672 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1673 sp<FakeWindowHandle> foregroundWindow =
1674 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001675 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001676 sp<FakeWindowHandle> wallpaperWindow =
1677 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001678 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001679 constexpr int expectedWallpaperFlags =
1680 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1681
1682 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1683 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1684 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1685 {100, 200}))
1686 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1687
1688 // Both foreground window and its wallpaper should receive the touch down
1689 foregroundWindow->consumeMotionDown();
1690 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1691
1692 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1693 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1694 ADISPLAY_ID_DEFAULT, {110, 200}))
1695 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1696
1697 foregroundWindow->consumeMotionMove();
1698 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1699
1700 // Wallpaper closes its channel, but the window remains.
1701 wallpaperWindow->destroyReceiver();
1702 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1703
1704 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1705 // is no longer valid.
1706 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1707 foregroundWindow->consumeMotionCancel();
1708}
1709
1710/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001711 * A single window that receives touch (on top), and a wallpaper window underneath it.
1712 * The top window gets a multitouch gesture.
1713 * Ensure that wallpaper gets the same gesture.
1714 */
1715TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1716 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1717 sp<FakeWindowHandle> window =
1718 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001719 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001720
1721 sp<FakeWindowHandle> wallpaperWindow =
1722 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001723 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001724 constexpr int expectedWallpaperFlags =
1725 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1726
1727 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1728
1729 // Touch down on top window
1730 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1731 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1732 {100, 100}))
1733 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1734
1735 // Both top window and its wallpaper should receive the touch down
1736 window->consumeMotionDown();
1737 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1738
1739 // Second finger down on the top window
1740 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001741 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001742 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1743 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1744 .x(100)
1745 .y(100))
1746 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1747 .x(150)
1748 .y(150))
1749 .build();
1750 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1751 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1752 InputEventInjectionSync::WAIT_FOR_RESULT))
1753 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1754
1755 window->consumeMotionPointerDown(1 /* pointerIndex */);
1756 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1757 expectedWallpaperFlags);
1758 window->assertNoEvents();
1759 wallpaperWindow->assertNoEvents();
1760}
1761
1762/**
1763 * Two windows: a window on the left and window on the right.
1764 * A third window, wallpaper, is behind both windows, and spans both top windows.
1765 * The first touch down goes to the left window. A second pointer touches down on the right window.
1766 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1767 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1768 * ACTION_POINTER_DOWN(1).
1769 */
1770TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1771 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1772 sp<FakeWindowHandle> leftWindow =
1773 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1774 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001775 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001776
1777 sp<FakeWindowHandle> rightWindow =
1778 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1779 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001780 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001781
1782 sp<FakeWindowHandle> wallpaperWindow =
1783 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1784 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001785 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001786 constexpr int expectedWallpaperFlags =
1787 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1788
1789 mDispatcher->setInputWindows(
1790 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1791
1792 // Touch down on left window
1793 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1794 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1795 {100, 100}))
1796 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1797
1798 // Both foreground window and its wallpaper should receive the touch down
1799 leftWindow->consumeMotionDown();
1800 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1801
1802 // Second finger down on the right window
1803 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001804 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001805 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1806 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1807 .x(100)
1808 .y(100))
1809 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1810 .x(300)
1811 .y(100))
1812 .build();
1813 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1814 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1815 InputEventInjectionSync::WAIT_FOR_RESULT))
1816 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1817
1818 leftWindow->consumeMotionMove();
1819 // Since the touch is split, right window gets ACTION_DOWN
1820 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1821 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1822 expectedWallpaperFlags);
1823
1824 // Now, leftWindow, which received the first finger, disappears.
1825 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1826 leftWindow->consumeMotionCancel();
1827 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1828 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1829
1830 // The pointer that's still down on the right window moves, and goes to the right window only.
1831 // As far as the dispatcher's concerned though, both pointers are still present.
1832 const MotionEvent secondFingerMoveEvent =
1833 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1834 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1835 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1836 .x(100)
1837 .y(100))
1838 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1839 .x(310)
1840 .y(110))
1841 .build();
1842 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1843 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1844 InputEventInjectionSync::WAIT_FOR_RESULT));
1845 rightWindow->consumeMotionMove();
1846
1847 leftWindow->assertNoEvents();
1848 rightWindow->assertNoEvents();
1849 wallpaperWindow->assertNoEvents();
1850}
1851
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001852/**
1853 * On the display, have a single window, and also an area where there's no window.
1854 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
1855 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
1856 */
1857TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
1858 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1859 sp<FakeWindowHandle> window =
1860 new FakeWindowHandle(application, mDispatcher, "Window", DISPLAY_ID);
1861
1862 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
1863 NotifyMotionArgs args;
1864
1865 // Touch down on the empty space
1866 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
1867
1868 mDispatcher->waitForIdle();
1869 window->assertNoEvents();
1870
1871 // Now touch down on the window with another pointer
1872 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
1873 mDispatcher->waitForIdle();
1874 window->consumeMotionDown();
1875}
1876
1877/**
1878 * Same test as above, but instead of touching the empty space, the first touch goes to
1879 * non-touchable window.
1880 */
1881TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
1882 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1883 sp<FakeWindowHandle> window1 =
1884 new FakeWindowHandle(application, mDispatcher, "Window1", DISPLAY_ID);
1885 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1886 window1->setTouchable(false);
1887 sp<FakeWindowHandle> window2 =
1888 new FakeWindowHandle(application, mDispatcher, "Window2", DISPLAY_ID);
1889 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1890
1891 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1892
1893 NotifyMotionArgs args;
1894 // Touch down on the non-touchable window
1895 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1896
1897 mDispatcher->waitForIdle();
1898 window1->assertNoEvents();
1899 window2->assertNoEvents();
1900
1901 // Now touch down on the window with another pointer
1902 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1903 mDispatcher->waitForIdle();
1904 window2->consumeMotionDown();
1905}
1906
Garfield Tandf26e862020-07-01 20:18:19 -07001907TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001908 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001909 sp<FakeWindowHandle> windowLeft =
1910 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1911 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001912 sp<FakeWindowHandle> windowRight =
1913 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1914 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001915
1916 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1917
1918 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1919
1920 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001921 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001922 injectMotionEvent(mDispatcher,
1923 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1924 AINPUT_SOURCE_MOUSE)
1925 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1926 .x(900)
1927 .y(400))
1928 .build()));
1929 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1930 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1931 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1932 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1933
1934 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001935 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001936 injectMotionEvent(mDispatcher,
1937 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1938 AINPUT_SOURCE_MOUSE)
1939 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1940 .x(300)
1941 .y(400))
1942 .build()));
1943 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1944 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1945 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1946 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1947 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1948 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1949
1950 // Inject a series of mouse events for a mouse click
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_DOWN, AINPUT_SOURCE_MOUSE)
1954 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1955 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1956 .x(300)
1957 .y(400))
1958 .build()));
1959 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1960
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001961 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001962 injectMotionEvent(mDispatcher,
1963 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1964 AINPUT_SOURCE_MOUSE)
1965 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1966 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1967 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1968 .x(300)
1969 .y(400))
1970 .build()));
1971 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1972 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1973
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001974 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001975 injectMotionEvent(mDispatcher,
1976 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1977 AINPUT_SOURCE_MOUSE)
1978 .buttonState(0)
1979 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1980 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1981 .x(300)
1982 .y(400))
1983 .build()));
1984 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1985 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1986
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001987 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001988 injectMotionEvent(mDispatcher,
1989 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1990 .buttonState(0)
1991 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1992 .x(300)
1993 .y(400))
1994 .build()));
1995 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1996
1997 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001998 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001999 injectMotionEvent(mDispatcher,
2000 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2001 AINPUT_SOURCE_MOUSE)
2002 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2003 .x(900)
2004 .y(400))
2005 .build()));
2006 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2007 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2008 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2009 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2010 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2011 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2012}
2013
2014// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2015// directly in this test.
2016TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002017 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002018 sp<FakeWindowHandle> window =
2019 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2020 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002021
2022 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2023
2024 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2025
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002026 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002027 injectMotionEvent(mDispatcher,
2028 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2029 AINPUT_SOURCE_MOUSE)
2030 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2031 .x(300)
2032 .y(400))
2033 .build()));
2034 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2035 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2036
2037 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002038 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002039 injectMotionEvent(mDispatcher,
2040 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2041 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2042 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2043 .x(300)
2044 .y(400))
2045 .build()));
2046 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2047
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002048 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002049 injectMotionEvent(mDispatcher,
2050 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2051 AINPUT_SOURCE_MOUSE)
2052 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2053 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2054 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2055 .x(300)
2056 .y(400))
2057 .build()));
2058 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2059 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2060
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002061 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002062 injectMotionEvent(mDispatcher,
2063 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2064 AINPUT_SOURCE_MOUSE)
2065 .buttonState(0)
2066 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2067 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2068 .x(300)
2069 .y(400))
2070 .build()));
2071 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2072 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2073
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002074 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002075 injectMotionEvent(mDispatcher,
2076 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2077 .buttonState(0)
2078 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2079 .x(300)
2080 .y(400))
2081 .build()));
2082 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2083
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002084 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002085 injectMotionEvent(mDispatcher,
2086 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2087 AINPUT_SOURCE_MOUSE)
2088 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2089 .x(300)
2090 .y(400))
2091 .build()));
2092 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2093 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2094}
2095
Garfield Tan00f511d2019-06-12 16:55:40 -07002096TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002097 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002098
2099 sp<FakeWindowHandle> windowLeft =
2100 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2101 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002102 sp<FakeWindowHandle> windowRight =
2103 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2104 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002105
2106 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2107
Arthur Hung72d8dc32020-03-28 00:48:39 +00002108 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002109
2110 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2111 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002112 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002113 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002114 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002115 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002116 windowRight->assertNoEvents();
2117}
2118
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002119TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002120 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002121 sp<FakeWindowHandle> window =
2122 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002123 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002124
Arthur Hung72d8dc32020-03-28 00:48:39 +00002125 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002126 setFocusedWindow(window);
2127
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002128 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002129
2130 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2131 mDispatcher->notifyKey(&keyArgs);
2132
2133 // Window should receive key down event.
2134 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2135
2136 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2137 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002138 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002139 mDispatcher->notifyDeviceReset(&args);
2140 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2141 AKEY_EVENT_FLAG_CANCELED);
2142}
2143
2144TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002145 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002146 sp<FakeWindowHandle> window =
2147 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2148
Arthur Hung72d8dc32020-03-28 00:48:39 +00002149 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002150
2151 NotifyMotionArgs motionArgs =
2152 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2153 ADISPLAY_ID_DEFAULT);
2154 mDispatcher->notifyMotion(&motionArgs);
2155
2156 // Window should receive motion down event.
2157 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2158
2159 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2160 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002161 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002162 mDispatcher->notifyDeviceReset(&args);
2163 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2164 0 /*expectedFlags*/);
2165}
2166
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002167/**
2168 * Ensure the correct coordinate spaces are used by InputDispatcher.
2169 *
2170 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2171 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2172 * space.
2173 */
2174class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2175public:
2176 void SetUp() override {
2177 InputDispatcherTest::SetUp();
2178 mDisplayInfos.clear();
2179 mWindowInfos.clear();
2180 }
2181
2182 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2183 gui::DisplayInfo info;
2184 info.displayId = displayId;
2185 info.transform = transform;
2186 mDisplayInfos.push_back(std::move(info));
2187 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2188 }
2189
2190 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2191 mWindowInfos.push_back(*windowHandle->getInfo());
2192 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2193 }
2194
2195 // Set up a test scenario where the display has a scaled projection and there are two windows
2196 // on the display.
2197 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2198 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2199 // respectively.
2200 ui::Transform displayTransform;
2201 displayTransform.set(2, 0, 0, 4);
2202 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2203
2204 std::shared_ptr<FakeApplicationHandle> application =
2205 std::make_shared<FakeApplicationHandle>();
2206
2207 // Add two windows to the display. Their frames are represented in the display space.
2208 sp<FakeWindowHandle> firstWindow =
2209 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002210 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2211 addWindow(firstWindow);
2212
2213 sp<FakeWindowHandle> secondWindow =
2214 new FakeWindowHandle(application, mDispatcher, "Second Window",
2215 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002216 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2217 addWindow(secondWindow);
2218 return {std::move(firstWindow), std::move(secondWindow)};
2219 }
2220
2221private:
2222 std::vector<gui::DisplayInfo> mDisplayInfos;
2223 std::vector<gui::WindowInfo> mWindowInfos;
2224};
2225
2226TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2227 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2228 // Send down to the first window. The point is represented in the display space. The point is
2229 // selected so that if the hit test was done with the transform applied to it, then it would
2230 // end up in the incorrect window.
2231 NotifyMotionArgs downMotionArgs =
2232 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2233 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2234 mDispatcher->notifyMotion(&downMotionArgs);
2235
2236 firstWindow->consumeMotionDown();
2237 secondWindow->assertNoEvents();
2238}
2239
2240// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2241// the event should be treated as being in the logical display space.
2242TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2243 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2244 // Send down to the first window. The point is represented in the logical display space. The
2245 // point is selected so that if the hit test was done in logical display space, then it would
2246 // end up in the incorrect window.
2247 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2248 PointF{75 * 2, 55 * 4});
2249
2250 firstWindow->consumeMotionDown();
2251 secondWindow->assertNoEvents();
2252}
2253
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002254// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2255// event should be treated as being in the logical display space.
2256TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2257 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2258
2259 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2260 ui::Transform injectedEventTransform;
2261 injectedEventTransform.set(matrix);
2262 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2263 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2264
2265 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2266 .displayId(ADISPLAY_ID_DEFAULT)
2267 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2268 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2269 .x(untransformedPoint.x)
2270 .y(untransformedPoint.y))
2271 .build();
2272 event.transform(matrix);
2273
2274 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2275 InputEventInjectionSync::WAIT_FOR_RESULT);
2276
2277 firstWindow->consumeMotionDown();
2278 secondWindow->assertNoEvents();
2279}
2280
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002281TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2282 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2283
2284 // Send down to the second window.
2285 NotifyMotionArgs downMotionArgs =
2286 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2287 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2288 mDispatcher->notifyMotion(&downMotionArgs);
2289
2290 firstWindow->assertNoEvents();
2291 const MotionEvent* event = secondWindow->consumeMotion();
2292 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2293
2294 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2295 EXPECT_EQ(300, event->getRawX(0));
2296 EXPECT_EQ(880, event->getRawY(0));
2297
2298 // Ensure that the x and y values are in the window's coordinate space.
2299 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2300 // the logical display space. This will be the origin of the window space.
2301 EXPECT_EQ(100, event->getX(0));
2302 EXPECT_EQ(80, event->getY(0));
2303}
2304
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002305using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2306 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002307
2308class TransferTouchFixture : public InputDispatcherTest,
2309 public ::testing::WithParamInterface<TransferFunction> {};
2310
2311TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002312 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002313
2314 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002315 sp<FakeWindowHandle> firstWindow =
2316 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2317 sp<FakeWindowHandle> secondWindow =
2318 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002319
2320 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002321 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002322
2323 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002324 NotifyMotionArgs downMotionArgs =
2325 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2326 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002327 mDispatcher->notifyMotion(&downMotionArgs);
2328 // Only the first window should get the down event
2329 firstWindow->consumeMotionDown();
2330 secondWindow->assertNoEvents();
2331
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002332 // Transfer touch to the second window
2333 TransferFunction f = GetParam();
2334 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2335 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002336 // The first window gets cancel and the second gets down
2337 firstWindow->consumeMotionCancel();
2338 secondWindow->consumeMotionDown();
2339
2340 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002341 NotifyMotionArgs upMotionArgs =
2342 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2343 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002344 mDispatcher->notifyMotion(&upMotionArgs);
2345 // The first window gets no events and the second gets up
2346 firstWindow->assertNoEvents();
2347 secondWindow->consumeMotionUp();
2348}
2349
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002350TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002351 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002352
2353 PointF touchPoint = {10, 10};
2354
2355 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002356 sp<FakeWindowHandle> firstWindow =
2357 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002358 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002359 sp<FakeWindowHandle> secondWindow =
2360 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002361 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002362
2363 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002364 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002365
2366 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002367 NotifyMotionArgs downMotionArgs =
2368 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2369 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002370 mDispatcher->notifyMotion(&downMotionArgs);
2371 // Only the first window should get the down event
2372 firstWindow->consumeMotionDown();
2373 secondWindow->assertNoEvents();
2374
2375 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002376 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002377 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002378 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002379 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2380 // Only the first window should get the pointer down event
2381 firstWindow->consumeMotionPointerDown(1);
2382 secondWindow->assertNoEvents();
2383
2384 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002385 TransferFunction f = GetParam();
2386 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2387 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002388 // The first window gets cancel and the second gets down and pointer down
2389 firstWindow->consumeMotionCancel();
2390 secondWindow->consumeMotionDown();
2391 secondWindow->consumeMotionPointerDown(1);
2392
2393 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002394 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002395 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002396 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002397 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2398 // The first window gets nothing and the second gets pointer up
2399 firstWindow->assertNoEvents();
2400 secondWindow->consumeMotionPointerUp(1);
2401
2402 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002403 NotifyMotionArgs upMotionArgs =
2404 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2405 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002406 mDispatcher->notifyMotion(&upMotionArgs);
2407 // The first window gets nothing and the second gets up
2408 firstWindow->assertNoEvents();
2409 secondWindow->consumeMotionUp();
2410}
2411
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002412// For the cases of single pointer touch and two pointers non-split touch, the api's
2413// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2414// for the case where there are multiple pointers split across several windows.
2415INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2416 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002417 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2418 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002419 return dispatcher->transferTouch(destChannelToken);
2420 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002421 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2422 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002423 return dispatcher->transferTouchFocus(from, to,
2424 false /*isDragAndDrop*/);
2425 }));
2426
Svet Ganov5d3bc372020-01-26 23:11:07 -08002427TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002428 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002429
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002430 sp<FakeWindowHandle> firstWindow =
2431 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002432 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002433
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002434 sp<FakeWindowHandle> secondWindow =
2435 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002436 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002437
2438 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002439 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002440
2441 PointF pointInFirst = {300, 200};
2442 PointF pointInSecond = {300, 600};
2443
2444 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002445 NotifyMotionArgs firstDownMotionArgs =
2446 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2447 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002448 mDispatcher->notifyMotion(&firstDownMotionArgs);
2449 // Only the first window should get the down event
2450 firstWindow->consumeMotionDown();
2451 secondWindow->assertNoEvents();
2452
2453 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002454 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002455 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002456 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002457 mDispatcher->notifyMotion(&secondDownMotionArgs);
2458 // The first window gets a move and the second a down
2459 firstWindow->consumeMotionMove();
2460 secondWindow->consumeMotionDown();
2461
2462 // Transfer touch focus to the second window
2463 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2464 // The first window gets cancel and the new gets pointer down (it already saw down)
2465 firstWindow->consumeMotionCancel();
2466 secondWindow->consumeMotionPointerDown(1);
2467
2468 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002469 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002470 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002471 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002472 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2473 // The first window gets nothing and the second gets pointer up
2474 firstWindow->assertNoEvents();
2475 secondWindow->consumeMotionPointerUp(1);
2476
2477 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002478 NotifyMotionArgs upMotionArgs =
2479 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2480 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002481 mDispatcher->notifyMotion(&upMotionArgs);
2482 // The first window gets nothing and the second gets up
2483 firstWindow->assertNoEvents();
2484 secondWindow->consumeMotionUp();
2485}
2486
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002487// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2488// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2489// touch is not supported, so the touch should continue on those windows and the transferred-to
2490// window should get nothing.
2491TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2492 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2493
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002494 sp<FakeWindowHandle> firstWindow =
2495 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2496 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002497
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002498 sp<FakeWindowHandle> secondWindow =
2499 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2500 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002501
2502 // Add the windows to the dispatcher
2503 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2504
2505 PointF pointInFirst = {300, 200};
2506 PointF pointInSecond = {300, 600};
2507
2508 // Send down to the first window
2509 NotifyMotionArgs firstDownMotionArgs =
2510 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2511 ADISPLAY_ID_DEFAULT, {pointInFirst});
2512 mDispatcher->notifyMotion(&firstDownMotionArgs);
2513 // Only the first window should get the down event
2514 firstWindow->consumeMotionDown();
2515 secondWindow->assertNoEvents();
2516
2517 // Send down to the second window
2518 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002519 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002520 {pointInFirst, pointInSecond});
2521 mDispatcher->notifyMotion(&secondDownMotionArgs);
2522 // The first window gets a move and the second a down
2523 firstWindow->consumeMotionMove();
2524 secondWindow->consumeMotionDown();
2525
2526 // Transfer touch focus to the second window
2527 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2528 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2529 ASSERT_FALSE(transferred);
2530 firstWindow->assertNoEvents();
2531 secondWindow->assertNoEvents();
2532
2533 // The rest of the dispatch should proceed as normal
2534 // Send pointer up to the second window
2535 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002536 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002537 {pointInFirst, pointInSecond});
2538 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2539 // The first window gets MOVE and the second gets pointer up
2540 firstWindow->consumeMotionMove();
2541 secondWindow->consumeMotionUp();
2542
2543 // Send up event to the first window
2544 NotifyMotionArgs upMotionArgs =
2545 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2546 ADISPLAY_ID_DEFAULT);
2547 mDispatcher->notifyMotion(&upMotionArgs);
2548 // The first window gets nothing and the second gets up
2549 firstWindow->consumeMotionUp();
2550 secondWindow->assertNoEvents();
2551}
2552
Arthur Hungabbb9d82021-09-01 14:52:30 +00002553// This case will create two windows and one mirrored window on the default display and mirror
2554// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2555// the windows info of second display before default display.
2556TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2557 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2558 sp<FakeWindowHandle> firstWindowInPrimary =
2559 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2560 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002561 sp<FakeWindowHandle> secondWindowInPrimary =
2562 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2563 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002564
2565 sp<FakeWindowHandle> mirrorWindowInPrimary =
2566 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2567 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002568
2569 sp<FakeWindowHandle> firstWindowInSecondary =
2570 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2571 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002572
2573 sp<FakeWindowHandle> secondWindowInSecondary =
2574 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2575 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002576
2577 // Update window info, let it find window handle of second display first.
2578 mDispatcher->setInputWindows(
2579 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2580 {ADISPLAY_ID_DEFAULT,
2581 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2582
2583 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2584 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2585 {50, 50}))
2586 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2587
2588 // Window should receive motion event.
2589 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2590
2591 // Transfer touch focus
2592 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2593 secondWindowInPrimary->getToken()));
2594 // The first window gets cancel.
2595 firstWindowInPrimary->consumeMotionCancel();
2596 secondWindowInPrimary->consumeMotionDown();
2597
2598 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2599 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2600 ADISPLAY_ID_DEFAULT, {150, 50}))
2601 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2602 firstWindowInPrimary->assertNoEvents();
2603 secondWindowInPrimary->consumeMotionMove();
2604
2605 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2606 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2607 {150, 50}))
2608 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2609 firstWindowInPrimary->assertNoEvents();
2610 secondWindowInPrimary->consumeMotionUp();
2611}
2612
2613// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2614// 'transferTouch' api.
2615TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2616 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2617 sp<FakeWindowHandle> firstWindowInPrimary =
2618 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2619 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002620 sp<FakeWindowHandle> secondWindowInPrimary =
2621 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2622 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002623
2624 sp<FakeWindowHandle> mirrorWindowInPrimary =
2625 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2626 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002627
2628 sp<FakeWindowHandle> firstWindowInSecondary =
2629 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2630 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002631
2632 sp<FakeWindowHandle> secondWindowInSecondary =
2633 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2634 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002635
2636 // Update window info, let it find window handle of second display first.
2637 mDispatcher->setInputWindows(
2638 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2639 {ADISPLAY_ID_DEFAULT,
2640 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2641
2642 // Touch on second display.
2643 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2644 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2645 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2646
2647 // Window should receive motion event.
2648 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2649
2650 // Transfer touch focus
2651 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2652
2653 // The first window gets cancel.
2654 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2655 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2656
2657 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2658 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2659 SECOND_DISPLAY_ID, {150, 50}))
2660 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2661 firstWindowInPrimary->assertNoEvents();
2662 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2663
2664 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2665 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2666 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2667 firstWindowInPrimary->assertNoEvents();
2668 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2669}
2670
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002671TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002672 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002673 sp<FakeWindowHandle> window =
2674 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2675
Vishnu Nair47074b82020-08-14 11:54:47 -07002676 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002677 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002678 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002679
2680 window->consumeFocusEvent(true);
2681
2682 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2683 mDispatcher->notifyKey(&keyArgs);
2684
2685 // Window should receive key down event.
2686 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2687}
2688
2689TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002690 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002691 sp<FakeWindowHandle> window =
2692 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2693
Arthur Hung72d8dc32020-03-28 00:48:39 +00002694 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002695
2696 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2697 mDispatcher->notifyKey(&keyArgs);
2698 mDispatcher->waitForIdle();
2699
2700 window->assertNoEvents();
2701}
2702
2703// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2704TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002705 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002706 sp<FakeWindowHandle> window =
2707 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2708
Arthur Hung72d8dc32020-03-28 00:48:39 +00002709 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002710
2711 // Send key
2712 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2713 mDispatcher->notifyKey(&keyArgs);
2714 // Send motion
2715 NotifyMotionArgs motionArgs =
2716 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2717 ADISPLAY_ID_DEFAULT);
2718 mDispatcher->notifyMotion(&motionArgs);
2719
2720 // Window should receive only the motion event
2721 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2722 window->assertNoEvents(); // Key event or focus event will not be received
2723}
2724
arthurhungea3f4fc2020-12-21 23:18:53 +08002725TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2726 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2727
arthurhungea3f4fc2020-12-21 23:18:53 +08002728 sp<FakeWindowHandle> firstWindow =
2729 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2730 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08002731
arthurhungea3f4fc2020-12-21 23:18:53 +08002732 sp<FakeWindowHandle> secondWindow =
2733 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2734 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08002735
2736 // Add the windows to the dispatcher
2737 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2738
2739 PointF pointInFirst = {300, 200};
2740 PointF pointInSecond = {300, 600};
2741
2742 // Send down to the first window
2743 NotifyMotionArgs firstDownMotionArgs =
2744 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2745 ADISPLAY_ID_DEFAULT, {pointInFirst});
2746 mDispatcher->notifyMotion(&firstDownMotionArgs);
2747 // Only the first window should get the down event
2748 firstWindow->consumeMotionDown();
2749 secondWindow->assertNoEvents();
2750
2751 // Send down to the second window
2752 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002753 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08002754 {pointInFirst, pointInSecond});
2755 mDispatcher->notifyMotion(&secondDownMotionArgs);
2756 // The first window gets a move and the second a down
2757 firstWindow->consumeMotionMove();
2758 secondWindow->consumeMotionDown();
2759
2760 // Send pointer cancel to the second window
2761 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002762 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08002763 {pointInFirst, pointInSecond});
2764 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2765 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2766 // The first window gets move and the second gets cancel.
2767 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2768 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2769
2770 // Send up event.
2771 NotifyMotionArgs upMotionArgs =
2772 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2773 ADISPLAY_ID_DEFAULT);
2774 mDispatcher->notifyMotion(&upMotionArgs);
2775 // The first window gets up and the second gets nothing.
2776 firstWindow->consumeMotionUp();
2777 secondWindow->assertNoEvents();
2778}
2779
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002780TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2781 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2782
2783 sp<FakeWindowHandle> window =
2784 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2785 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2786 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2787 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2788 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2789
2790 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2791 window->assertNoEvents();
2792 mDispatcher->waitForIdle();
2793}
2794
chaviwd1c23182019-12-20 18:44:56 -08002795class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002796public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002797 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002798 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07002799 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002800 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002801 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002802 }
2803
chaviwd1c23182019-12-20 18:44:56 -08002804 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2805
2806 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2807 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2808 expectedDisplayId, expectedFlags);
2809 }
2810
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002811 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2812
2813 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2814
chaviwd1c23182019-12-20 18:44:56 -08002815 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2816 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2817 expectedDisplayId, expectedFlags);
2818 }
2819
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002820 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2821 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2822 expectedDisplayId, expectedFlags);
2823 }
2824
chaviwd1c23182019-12-20 18:44:56 -08002825 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2826 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2827 expectedDisplayId, expectedFlags);
2828 }
2829
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002830 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2831 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2832 expectedDisplayId, expectedFlags);
2833 }
2834
Arthur Hungfbfa5722021-11-16 02:45:54 +00002835 void consumeMotionPointerDown(int32_t pointerIdx) {
2836 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2837 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2838 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2839 0 /*expectedFlags*/);
2840 }
2841
Evan Rosky84f07f02021-04-16 10:42:42 -07002842 MotionEvent* consumeMotion() {
2843 InputEvent* event = mInputReceiver->consume();
2844 if (!event) {
2845 ADD_FAILURE() << "No event was produced";
2846 return nullptr;
2847 }
2848 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2849 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2850 return nullptr;
2851 }
2852 return static_cast<MotionEvent*>(event);
2853 }
2854
chaviwd1c23182019-12-20 18:44:56 -08002855 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2856
2857private:
2858 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002859};
2860
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002861using InputDispatcherMonitorTest = InputDispatcherTest;
2862
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002863/**
2864 * Two entities that receive touch: A window, and a global monitor.
2865 * The touch goes to the window, and then the window disappears.
2866 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2867 * for the monitor, as well.
2868 * 1. foregroundWindow
2869 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2870 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002871TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002872 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2873 sp<FakeWindowHandle> window =
2874 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2875
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002876 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002877
2878 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2879 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2880 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2881 {100, 200}))
2882 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2883
2884 // Both the foreground window and the global monitor should receive the touch down
2885 window->consumeMotionDown();
2886 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2887
2888 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2889 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2890 ADISPLAY_ID_DEFAULT, {110, 200}))
2891 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2892
2893 window->consumeMotionMove();
2894 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2895
2896 // Now the foreground window goes away
2897 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2898 window->consumeMotionCancel();
2899 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2900
2901 // If more events come in, there will be no more foreground window to send them to. This will
2902 // cause a cancel for the monitor, as well.
2903 ASSERT_EQ(InputEventInjectionResult::FAILED,
2904 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2905 ADISPLAY_ID_DEFAULT, {120, 200}))
2906 << "Injection should fail because the window was removed";
2907 window->assertNoEvents();
2908 // Global monitor now gets the cancel
2909 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2910}
2911
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002912TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002913 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002914 sp<FakeWindowHandle> window =
2915 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002916 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002917
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002918 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002919
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002920 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002921 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002922 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002923 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002924 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002925}
2926
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002927TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
2928 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002929
Chris Yea209fde2020-07-22 13:54:51 -07002930 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002931 sp<FakeWindowHandle> window =
2932 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002933 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002934
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002935 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002936 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002937 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002938 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002939 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002940
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002941 // Pilfer pointers from the monitor.
2942 // This should not do anything and the window should continue to receive events.
2943 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00002944
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002945 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002946 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2947 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002948 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002949
2950 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2951 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002952}
2953
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002954TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07002955 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2956 sp<FakeWindowHandle> window =
2957 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2958 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2959 window->setWindowOffset(20, 40);
2960 window->setWindowTransform(0, 1, -1, 0);
2961
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002962 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07002963
2964 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2965 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2966 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2967 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2968 MotionEvent* event = monitor.consumeMotion();
2969 // Even though window has transform, gesture monitor must not.
2970 ASSERT_EQ(ui::Transform(), event->getTransform());
2971}
2972
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002973TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002974 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002975 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00002976
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002977 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00002978 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002979 << "Injection should fail if there is a monitor, but no touchable window";
2980 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00002981}
2982
chaviw81e2bb92019-12-18 15:03:51 -08002983TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002984 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002985 sp<FakeWindowHandle> window =
2986 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2987
Arthur Hung72d8dc32020-03-28 00:48:39 +00002988 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002989
2990 NotifyMotionArgs motionArgs =
2991 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2992 ADISPLAY_ID_DEFAULT);
2993
2994 mDispatcher->notifyMotion(&motionArgs);
2995 // Window should receive motion down event.
2996 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2997
2998 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002999 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003000 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3001 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3002 motionArgs.pointerCoords[0].getX() - 10);
3003
3004 mDispatcher->notifyMotion(&motionArgs);
3005 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3006 0 /*expectedFlags*/);
3007}
3008
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003009/**
3010 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3011 * the device default right away. In the test scenario, we check both the default value,
3012 * and the action of enabling / disabling.
3013 */
3014TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003015 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003016 sp<FakeWindowHandle> window =
3017 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003018 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003019
3020 // Set focused application.
3021 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003022 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003023
3024 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003025 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003026 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003027 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3028
3029 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003030 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003031 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003032 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3033
3034 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003035 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3036 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003037 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003038 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003039 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003040 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003041 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3042
3043 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003044 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003045 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003046 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3047
3048 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003049 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3050 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003051 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003052 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003053 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003054 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003055 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3056
3057 window->assertNoEvents();
3058}
3059
Gang Wange9087892020-01-07 12:17:14 -05003060TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003061 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003062 sp<FakeWindowHandle> window =
3063 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3064
3065 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003066 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003067
Arthur Hung72d8dc32020-03-28 00:48:39 +00003068 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003069 setFocusedWindow(window);
3070
Gang Wange9087892020-01-07 12:17:14 -05003071 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3072
3073 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3074 mDispatcher->notifyKey(&keyArgs);
3075
3076 InputEvent* event = window->consume();
3077 ASSERT_NE(event, nullptr);
3078
3079 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3080 ASSERT_NE(verified, nullptr);
3081 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3082
3083 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3084 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3085 ASSERT_EQ(keyArgs.source, verified->source);
3086 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3087
3088 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3089
3090 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003091 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003092 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003093 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3094 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3095 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3096 ASSERT_EQ(0, verifiedKey.repeatCount);
3097}
3098
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003099TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003100 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003101 sp<FakeWindowHandle> window =
3102 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3103
3104 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3105
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003106 ui::Transform transform;
3107 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3108
3109 gui::DisplayInfo displayInfo;
3110 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3111 displayInfo.transform = transform;
3112
3113 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003114
3115 NotifyMotionArgs motionArgs =
3116 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3117 ADISPLAY_ID_DEFAULT);
3118 mDispatcher->notifyMotion(&motionArgs);
3119
3120 InputEvent* event = window->consume();
3121 ASSERT_NE(event, nullptr);
3122
3123 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3124 ASSERT_NE(verified, nullptr);
3125 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3126
3127 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3128 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3129 EXPECT_EQ(motionArgs.source, verified->source);
3130 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3131
3132 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3133
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003134 const vec2 rawXY =
3135 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3136 motionArgs.pointerCoords[0].getXYValue());
3137 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3138 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003139 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003140 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003141 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003142 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3143 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3144}
3145
chaviw09c8d2d2020-08-24 15:48:26 -07003146/**
3147 * Ensure that separate calls to sign the same data are generating the same key.
3148 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3149 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3150 * tests.
3151 */
3152TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3153 KeyEvent event = getTestKeyEvent();
3154 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3155
3156 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3157 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3158 ASSERT_EQ(hmac1, hmac2);
3159}
3160
3161/**
3162 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3163 */
3164TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3165 KeyEvent event = getTestKeyEvent();
3166 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3167 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3168
3169 verifiedEvent.deviceId += 1;
3170 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3171
3172 verifiedEvent.source += 1;
3173 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3174
3175 verifiedEvent.eventTimeNanos += 1;
3176 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3177
3178 verifiedEvent.displayId += 1;
3179 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3180
3181 verifiedEvent.action += 1;
3182 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3183
3184 verifiedEvent.downTimeNanos += 1;
3185 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3186
3187 verifiedEvent.flags += 1;
3188 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3189
3190 verifiedEvent.keyCode += 1;
3191 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3192
3193 verifiedEvent.scanCode += 1;
3194 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3195
3196 verifiedEvent.metaState += 1;
3197 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3198
3199 verifiedEvent.repeatCount += 1;
3200 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3201}
3202
Vishnu Nair958da932020-08-21 17:12:37 -07003203TEST_F(InputDispatcherTest, SetFocusedWindow) {
3204 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3205 sp<FakeWindowHandle> windowTop =
3206 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3207 sp<FakeWindowHandle> windowSecond =
3208 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3209 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3210
3211 // Top window is also focusable but is not granted focus.
3212 windowTop->setFocusable(true);
3213 windowSecond->setFocusable(true);
3214 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3215 setFocusedWindow(windowSecond);
3216
3217 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003218 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3219 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003220
3221 // Focused window should receive event.
3222 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3223 windowTop->assertNoEvents();
3224}
3225
3226TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3227 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3228 sp<FakeWindowHandle> window =
3229 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3230 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3231
3232 window->setFocusable(true);
3233 // Release channel for window is no longer valid.
3234 window->releaseChannel();
3235 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3236 setFocusedWindow(window);
3237
3238 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003239 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3240 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003241
3242 // window channel is invalid, so it should not receive any input event.
3243 window->assertNoEvents();
3244}
3245
3246TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3247 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3248 sp<FakeWindowHandle> window =
3249 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003250 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003251 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3252
Vishnu Nair958da932020-08-21 17:12:37 -07003253 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3254 setFocusedWindow(window);
3255
3256 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003257 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3258 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003259
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003260 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003261 window->assertNoEvents();
3262}
3263
3264TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3265 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3266 sp<FakeWindowHandle> windowTop =
3267 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3268 sp<FakeWindowHandle> windowSecond =
3269 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3270 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3271
3272 windowTop->setFocusable(true);
3273 windowSecond->setFocusable(true);
3274 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3275 setFocusedWindow(windowTop);
3276 windowTop->consumeFocusEvent(true);
3277
3278 setFocusedWindow(windowSecond, windowTop);
3279 windowSecond->consumeFocusEvent(true);
3280 windowTop->consumeFocusEvent(false);
3281
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003282 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3283 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003284
3285 // Focused window should receive event.
3286 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3287}
3288
3289TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3290 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3291 sp<FakeWindowHandle> windowTop =
3292 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3293 sp<FakeWindowHandle> windowSecond =
3294 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3295 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3296
3297 windowTop->setFocusable(true);
3298 windowSecond->setFocusable(true);
3299 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3300 setFocusedWindow(windowSecond, windowTop);
3301
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003302 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3303 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003304
3305 // Event should be dropped.
3306 windowTop->assertNoEvents();
3307 windowSecond->assertNoEvents();
3308}
3309
3310TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3311 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3312 sp<FakeWindowHandle> window =
3313 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3314 sp<FakeWindowHandle> previousFocusedWindow =
3315 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3316 ADISPLAY_ID_DEFAULT);
3317 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3318
3319 window->setFocusable(true);
3320 previousFocusedWindow->setFocusable(true);
3321 window->setVisible(false);
3322 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3323 setFocusedWindow(previousFocusedWindow);
3324 previousFocusedWindow->consumeFocusEvent(true);
3325
3326 // Requesting focus on invisible window takes focus from currently focused window.
3327 setFocusedWindow(window);
3328 previousFocusedWindow->consumeFocusEvent(false);
3329
3330 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003331 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003332 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003333 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003334
3335 // Window does not get focus event or key down.
3336 window->assertNoEvents();
3337
3338 // Window becomes visible.
3339 window->setVisible(true);
3340 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3341
3342 // Window receives focus event.
3343 window->consumeFocusEvent(true);
3344 // Focused window receives key down.
3345 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3346}
3347
Vishnu Nair599f1412021-06-21 10:39:58 -07003348TEST_F(InputDispatcherTest, DisplayRemoved) {
3349 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3350 sp<FakeWindowHandle> window =
3351 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3352 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3353
3354 // window is granted focus.
3355 window->setFocusable(true);
3356 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3357 setFocusedWindow(window);
3358 window->consumeFocusEvent(true);
3359
3360 // When a display is removed window loses focus.
3361 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3362 window->consumeFocusEvent(false);
3363}
3364
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003365/**
3366 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3367 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3368 * of the 'slipperyEnterWindow'.
3369 *
3370 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3371 * a way so that the touched location is no longer covered by the top window.
3372 *
3373 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3374 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3375 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3376 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3377 * with ACTION_DOWN).
3378 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3379 * window moved itself away from the touched location and had Flag::SLIPPERY.
3380 *
3381 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3382 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3383 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3384 *
3385 * In this test, we ensure that the event received by the bottom window has
3386 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3387 */
3388TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3389 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3390 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3391
3392 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3393 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3394
3395 sp<FakeWindowHandle> slipperyExitWindow =
3396 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003397 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003398 // Make sure this one overlaps the bottom window
3399 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3400 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3401 // one. Windows with the same owner are not considered to be occluding each other.
3402 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3403
3404 sp<FakeWindowHandle> slipperyEnterWindow =
3405 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3406 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3407
3408 mDispatcher->setInputWindows(
3409 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3410
3411 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3412 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3413 ADISPLAY_ID_DEFAULT, {{50, 50}});
3414 mDispatcher->notifyMotion(&args);
3415 slipperyExitWindow->consumeMotionDown();
3416 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3417 mDispatcher->setInputWindows(
3418 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3419
3420 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3421 ADISPLAY_ID_DEFAULT, {{51, 51}});
3422 mDispatcher->notifyMotion(&args);
3423
3424 slipperyExitWindow->consumeMotionCancel();
3425
3426 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3427 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3428}
3429
Garfield Tan1c7bc862020-01-28 13:24:04 -08003430class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3431protected:
3432 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3433 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3434
Chris Yea209fde2020-07-22 13:54:51 -07003435 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003436 sp<FakeWindowHandle> mWindow;
3437
3438 virtual void SetUp() override {
3439 mFakePolicy = new FakeInputDispatcherPolicy();
3440 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003441 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003442 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3443 ASSERT_EQ(OK, mDispatcher->start());
3444
3445 setUpWindow();
3446 }
3447
3448 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003449 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003450 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3451
Vishnu Nair47074b82020-08-14 11:54:47 -07003452 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003453 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003454 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003455 mWindow->consumeFocusEvent(true);
3456 }
3457
Chris Ye2ad95392020-09-01 13:44:44 -07003458 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003459 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003460 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003461 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3462 mDispatcher->notifyKey(&keyArgs);
3463
3464 // Window should receive key down event.
3465 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3466 }
3467
3468 void expectKeyRepeatOnce(int32_t repeatCount) {
3469 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3470 InputEvent* repeatEvent = mWindow->consume();
3471 ASSERT_NE(nullptr, repeatEvent);
3472
3473 uint32_t eventType = repeatEvent->getType();
3474 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3475
3476 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3477 uint32_t eventAction = repeatKeyEvent->getAction();
3478 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3479 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3480 }
3481
Chris Ye2ad95392020-09-01 13:44:44 -07003482 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003483 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003484 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003485 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3486 mDispatcher->notifyKey(&keyArgs);
3487
3488 // Window should receive key down event.
3489 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3490 0 /*expectedFlags*/);
3491 }
3492};
3493
3494TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003495 sendAndConsumeKeyDown(1 /* deviceId */);
3496 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3497 expectKeyRepeatOnce(repeatCount);
3498 }
3499}
3500
3501TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3502 sendAndConsumeKeyDown(1 /* deviceId */);
3503 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3504 expectKeyRepeatOnce(repeatCount);
3505 }
3506 sendAndConsumeKeyDown(2 /* deviceId */);
3507 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003508 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3509 expectKeyRepeatOnce(repeatCount);
3510 }
3511}
3512
3513TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003514 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003515 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003516 sendAndConsumeKeyUp(1 /* deviceId */);
3517 mWindow->assertNoEvents();
3518}
3519
3520TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3521 sendAndConsumeKeyDown(1 /* deviceId */);
3522 expectKeyRepeatOnce(1 /*repeatCount*/);
3523 sendAndConsumeKeyDown(2 /* deviceId */);
3524 expectKeyRepeatOnce(1 /*repeatCount*/);
3525 // Stale key up from device 1.
3526 sendAndConsumeKeyUp(1 /* deviceId */);
3527 // Device 2 is still down, keep repeating
3528 expectKeyRepeatOnce(2 /*repeatCount*/);
3529 expectKeyRepeatOnce(3 /*repeatCount*/);
3530 // Device 2 key up
3531 sendAndConsumeKeyUp(2 /* deviceId */);
3532 mWindow->assertNoEvents();
3533}
3534
3535TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3536 sendAndConsumeKeyDown(1 /* deviceId */);
3537 expectKeyRepeatOnce(1 /*repeatCount*/);
3538 sendAndConsumeKeyDown(2 /* deviceId */);
3539 expectKeyRepeatOnce(1 /*repeatCount*/);
3540 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3541 sendAndConsumeKeyUp(2 /* deviceId */);
3542 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003543 mWindow->assertNoEvents();
3544}
3545
liushenxiang42232912021-05-21 20:24:09 +08003546TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3547 sendAndConsumeKeyDown(DEVICE_ID);
3548 expectKeyRepeatOnce(1 /*repeatCount*/);
3549 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3550 mDispatcher->notifyDeviceReset(&args);
3551 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3552 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3553 mWindow->assertNoEvents();
3554}
3555
Garfield Tan1c7bc862020-01-28 13:24:04 -08003556TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003557 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003558 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3559 InputEvent* repeatEvent = mWindow->consume();
3560 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3561 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3562 IdGenerator::getSource(repeatEvent->getId()));
3563 }
3564}
3565
3566TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003567 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003568
3569 std::unordered_set<int32_t> idSet;
3570 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3571 InputEvent* repeatEvent = mWindow->consume();
3572 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3573 int32_t id = repeatEvent->getId();
3574 EXPECT_EQ(idSet.end(), idSet.find(id));
3575 idSet.insert(id);
3576 }
3577}
3578
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003579/* Test InputDispatcher for MultiDisplay */
3580class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3581public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003582 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003583 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003584
Chris Yea209fde2020-07-22 13:54:51 -07003585 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003586 windowInPrimary =
3587 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003588
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003589 // Set focus window for primary display, but focused display would be second one.
3590 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003591 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003592 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003593 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003594 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003595
Chris Yea209fde2020-07-22 13:54:51 -07003596 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003597 windowInSecondary =
3598 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003599 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003600 // Set focus display to second one.
3601 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3602 // Set focus window for second display.
3603 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003604 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003605 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003606 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003607 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003608 }
3609
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003610 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003611 InputDispatcherTest::TearDown();
3612
Chris Yea209fde2020-07-22 13:54:51 -07003613 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003614 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003615 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003616 windowInSecondary.clear();
3617 }
3618
3619protected:
Chris Yea209fde2020-07-22 13:54:51 -07003620 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003621 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003622 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003623 sp<FakeWindowHandle> windowInSecondary;
3624};
3625
3626TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3627 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003628 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3629 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3630 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003631 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003632 windowInSecondary->assertNoEvents();
3633
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003634 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003635 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3636 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3637 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003638 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003639 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003640}
3641
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003642TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003643 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003644 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3645 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003646 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003647 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003648 windowInSecondary->assertNoEvents();
3649
3650 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003651 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003652 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003653 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003654 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003655
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003656 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003657 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003658
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003659 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003660 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3661 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003662
3663 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003664 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003665 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003666 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003667 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003668 windowInSecondary->assertNoEvents();
3669}
3670
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003671// Test per-display input monitors for motion event.
3672TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003673 FakeMonitorReceiver monitorInPrimary =
3674 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3675 FakeMonitorReceiver monitorInSecondary =
3676 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003677
3678 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003679 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3680 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3681 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003682 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003683 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003684 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003685 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003686
3687 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003688 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3689 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3690 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003691 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003692 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003693 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003694 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003695
3696 // Test inject a non-pointer motion event.
3697 // If specific a display, it will dispatch to the focused window of particular display,
3698 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003699 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3700 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3701 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003702 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003703 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003704 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003705 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003706}
3707
3708// Test per-display input monitors for key event.
3709TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003710 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003711 FakeMonitorReceiver monitorInPrimary =
3712 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3713 FakeMonitorReceiver monitorInSecondary =
3714 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003715
3716 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003717 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3718 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003719 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003720 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003721 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003722 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003723}
3724
Vishnu Nair958da932020-08-21 17:12:37 -07003725TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3726 sp<FakeWindowHandle> secondWindowInPrimary =
3727 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3728 secondWindowInPrimary->setFocusable(true);
3729 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3730 setFocusedWindow(secondWindowInPrimary);
3731 windowInPrimary->consumeFocusEvent(false);
3732 secondWindowInPrimary->consumeFocusEvent(true);
3733
3734 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003735 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3736 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003737 windowInPrimary->assertNoEvents();
3738 windowInSecondary->assertNoEvents();
3739 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3740}
3741
Arthur Hungdfd528e2021-12-08 13:23:04 +00003742TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3743 FakeMonitorReceiver monitorInPrimary =
3744 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3745 FakeMonitorReceiver monitorInSecondary =
3746 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3747
3748 // Test touch down on primary display.
3749 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3750 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3751 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3752 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3753 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3754
3755 // Test touch down on second display.
3756 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3757 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3758 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3759 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3760 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3761
3762 // Trigger cancel touch.
3763 mDispatcher->cancelCurrentTouch();
3764 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3765 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3766 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3767 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3768
3769 // Test inject a move motion event, no window/monitor should receive the event.
3770 ASSERT_EQ(InputEventInjectionResult::FAILED,
3771 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3772 ADISPLAY_ID_DEFAULT, {110, 200}))
3773 << "Inject motion event should return InputEventInjectionResult::FAILED";
3774 windowInPrimary->assertNoEvents();
3775 monitorInPrimary.assertNoEvents();
3776
3777 ASSERT_EQ(InputEventInjectionResult::FAILED,
3778 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3779 SECOND_DISPLAY_ID, {110, 200}))
3780 << "Inject motion event should return InputEventInjectionResult::FAILED";
3781 windowInSecondary->assertNoEvents();
3782 monitorInSecondary.assertNoEvents();
3783}
3784
Jackal Guof9696682018-10-05 12:23:23 +08003785class InputFilterTest : public InputDispatcherTest {
3786protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003787 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3788 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003789 NotifyMotionArgs motionArgs;
3790
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003791 motionArgs =
3792 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003793 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003794 motionArgs =
3795 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003796 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003797 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003798 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003799 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3800 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003801 } else {
3802 mFakePolicy->assertFilterInputEventWasNotCalled();
3803 }
3804 }
3805
3806 void testNotifyKey(bool expectToBeFiltered) {
3807 NotifyKeyArgs keyArgs;
3808
3809 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3810 mDispatcher->notifyKey(&keyArgs);
3811 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3812 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003813 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003814
3815 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003816 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003817 } else {
3818 mFakePolicy->assertFilterInputEventWasNotCalled();
3819 }
3820 }
3821};
3822
3823// Test InputFilter for MotionEvent
3824TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3825 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3826 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3827 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3828
3829 // Enable InputFilter
3830 mDispatcher->setInputFilterEnabled(true);
3831 // Test touch on both primary and second display, and check if both events are filtered.
3832 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3833 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3834
3835 // Disable InputFilter
3836 mDispatcher->setInputFilterEnabled(false);
3837 // Test touch on both primary and second display, and check if both events aren't filtered.
3838 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3839 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3840}
3841
3842// Test InputFilter for KeyEvent
3843TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3844 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3845 testNotifyKey(/*expectToBeFiltered*/ false);
3846
3847 // Enable InputFilter
3848 mDispatcher->setInputFilterEnabled(true);
3849 // Send a key event, and check if it is filtered.
3850 testNotifyKey(/*expectToBeFiltered*/ true);
3851
3852 // Disable InputFilter
3853 mDispatcher->setInputFilterEnabled(false);
3854 // Send a key event, and check if it isn't filtered.
3855 testNotifyKey(/*expectToBeFiltered*/ false);
3856}
3857
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003858// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3859// logical display coordinate space.
3860TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3861 ui::Transform firstDisplayTransform;
3862 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3863 ui::Transform secondDisplayTransform;
3864 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3865
3866 std::vector<gui::DisplayInfo> displayInfos(2);
3867 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3868 displayInfos[0].transform = firstDisplayTransform;
3869 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3870 displayInfos[1].transform = secondDisplayTransform;
3871
3872 mDispatcher->onWindowInfosChanged({}, displayInfos);
3873
3874 // Enable InputFilter
3875 mDispatcher->setInputFilterEnabled(true);
3876
3877 // Ensure the correct transforms are used for the displays.
3878 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3879 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3880}
3881
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003882class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3883protected:
3884 virtual void SetUp() override {
3885 InputDispatcherTest::SetUp();
3886
3887 /**
3888 * We don't need to enable input filter to test the injected event policy, but we enabled it
3889 * here to make the tests more realistic, since this policy only matters when inputfilter is
3890 * on.
3891 */
3892 mDispatcher->setInputFilterEnabled(true);
3893
3894 std::shared_ptr<InputApplicationHandle> application =
3895 std::make_shared<FakeApplicationHandle>();
3896 mWindow =
3897 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3898
3899 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3900 mWindow->setFocusable(true);
3901 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3902 setFocusedWindow(mWindow);
3903 mWindow->consumeFocusEvent(true);
3904 }
3905
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003906 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3907 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003908 KeyEvent event;
3909
3910 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3911 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3912 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3913 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3914 const int32_t additionalPolicyFlags =
3915 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3916 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3917 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3918 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3919 policyFlags | additionalPolicyFlags));
3920
3921 InputEvent* received = mWindow->consume();
3922 ASSERT_NE(nullptr, received);
3923 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003924 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3925 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3926 ASSERT_EQ(flags, keyEvent.getFlags());
3927 }
3928
3929 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3930 int32_t flags) {
3931 MotionEvent event;
3932 PointerProperties pointerProperties[1];
3933 PointerCoords pointerCoords[1];
3934 pointerProperties[0].clear();
3935 pointerProperties[0].id = 0;
3936 pointerCoords[0].clear();
3937 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3938 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3939
3940 ui::Transform identityTransform;
3941 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3942 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3943 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3944 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3945 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003946 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003947 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003948 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3949
3950 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3951 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3952 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3953 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3954 policyFlags | additionalPolicyFlags));
3955
3956 InputEvent* received = mWindow->consume();
3957 ASSERT_NE(nullptr, received);
3958 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3959 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3960 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3961 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003962 }
3963
3964private:
3965 sp<FakeWindowHandle> mWindow;
3966};
3967
3968TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003969 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3970 // filter. Without it, the event will no different from a regularly injected event, and the
3971 // injected device id will be overwritten.
3972 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3973 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003974}
3975
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003976TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003977 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003978 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3979 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3980}
3981
3982TEST_F(InputFilterInjectionPolicyTest,
3983 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3984 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3985 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3986 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003987}
3988
3989TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3990 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003991 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003992}
3993
chaviwfd6d3512019-03-25 13:23:49 -07003994class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003995 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003996 InputDispatcherTest::SetUp();
3997
Chris Yea209fde2020-07-22 13:54:51 -07003998 std::shared_ptr<FakeApplicationHandle> application =
3999 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004000 mUnfocusedWindow =
4001 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004002 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004003
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004004 mFocusedWindow =
4005 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4006 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004007
4008 // Set focused application.
4009 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004010 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004011
4012 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004013 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004014 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004015 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004016 }
4017
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004018 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004019 InputDispatcherTest::TearDown();
4020
4021 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004022 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004023 }
4024
4025protected:
4026 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004027 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004028 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004029};
4030
4031// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4032// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4033// the onPointerDownOutsideFocus callback.
4034TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004035 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004036 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4037 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004038 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004039 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004040
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004041 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004042 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4043}
4044
4045// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4046// DOWN on the window that doesn't have focus. Ensure no window received the
4047// onPointerDownOutsideFocus callback.
4048TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004049 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004050 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004051 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004052 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004053
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004054 ASSERT_TRUE(mDispatcher->waitForIdle());
4055 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004056}
4057
4058// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4059// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4060TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004061 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4062 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004063 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004064 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004065
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004066 ASSERT_TRUE(mDispatcher->waitForIdle());
4067 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004068}
4069
4070// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4071// DOWN on the window that already has focus. Ensure no window received the
4072// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004073TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004074 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004075 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004076 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004077 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004078 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004079
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004080 ASSERT_TRUE(mDispatcher->waitForIdle());
4081 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004082}
4083
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004084// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4085// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4086TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4087 const MotionEvent event =
4088 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4089 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4090 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4091 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4092 .build();
4093 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4094 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4095 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4096
4097 ASSERT_TRUE(mDispatcher->waitForIdle());
4098 mFakePolicy->assertOnPointerDownWasNotCalled();
4099 // Ensure that the unfocused window did not receive any FOCUS events.
4100 mUnfocusedWindow->assertNoEvents();
4101}
4102
chaviwaf87b3e2019-10-01 16:59:28 -07004103// These tests ensures we can send touch events to a single client when there are multiple input
4104// windows that point to the same client token.
4105class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4106 virtual void SetUp() override {
4107 InputDispatcherTest::SetUp();
4108
Chris Yea209fde2020-07-22 13:54:51 -07004109 std::shared_ptr<FakeApplicationHandle> application =
4110 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004111 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4112 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004113 mWindow1->setFrame(Rect(0, 0, 100, 100));
4114
4115 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4116 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004117 mWindow2->setFrame(Rect(100, 100, 200, 200));
4118
Arthur Hung72d8dc32020-03-28 00:48:39 +00004119 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004120 }
4121
4122protected:
4123 sp<FakeWindowHandle> mWindow1;
4124 sp<FakeWindowHandle> mWindow2;
4125
4126 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004127 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004128 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4129 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004130 }
4131
4132 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4133 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004134 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004135 InputEvent* event = window->consume();
4136
4137 ASSERT_NE(nullptr, event) << name.c_str()
4138 << ": consumer should have returned non-NULL event.";
4139
4140 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4141 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4142 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4143
4144 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004145 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004146
4147 for (size_t i = 0; i < points.size(); i++) {
4148 float expectedX = points[i].x;
4149 float expectedY = points[i].y;
4150
4151 EXPECT_EQ(expectedX, motionEvent.getX(i))
4152 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4153 << ", got " << motionEvent.getX(i);
4154 EXPECT_EQ(expectedY, motionEvent.getY(i))
4155 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4156 << ", got " << motionEvent.getY(i);
4157 }
4158 }
chaviw9eaa22c2020-07-01 16:21:27 -07004159
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004160 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004161 std::vector<PointF> expectedPoints) {
4162 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4163 ADISPLAY_ID_DEFAULT, touchedPoints);
4164 mDispatcher->notifyMotion(&motionArgs);
4165
4166 // Always consume from window1 since it's the window that has the InputReceiver
4167 consumeMotionEvent(mWindow1, action, expectedPoints);
4168 }
chaviwaf87b3e2019-10-01 16:59:28 -07004169};
4170
4171TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4172 // Touch Window 1
4173 PointF touchedPoint = {10, 10};
4174 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004175 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004176
4177 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004178 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004179
4180 // Touch Window 2
4181 touchedPoint = {150, 150};
4182 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004183 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004184}
4185
chaviw9eaa22c2020-07-01 16:21:27 -07004186TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4187 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004188 mWindow2->setWindowScale(0.5f, 0.5f);
4189
4190 // Touch Window 1
4191 PointF touchedPoint = {10, 10};
4192 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004193 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004194 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004195 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004196
4197 // Touch Window 2
4198 touchedPoint = {150, 150};
4199 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004200 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4201 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004202
chaviw9eaa22c2020-07-01 16:21:27 -07004203 // Update the transform so rotation is set
4204 mWindow2->setWindowTransform(0, -1, 1, 0);
4205 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4206 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004207}
4208
chaviw9eaa22c2020-07-01 16:21:27 -07004209TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004210 mWindow2->setWindowScale(0.5f, 0.5f);
4211
4212 // Touch Window 1
4213 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4214 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004215 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004216
4217 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004218 touchedPoints.push_back(PointF{150, 150});
4219 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004220 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004221
chaviw9eaa22c2020-07-01 16:21:27 -07004222 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004223 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004224 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004225
chaviw9eaa22c2020-07-01 16:21:27 -07004226 // Update the transform so rotation is set for Window 2
4227 mWindow2->setWindowTransform(0, -1, 1, 0);
4228 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004229 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004230}
4231
chaviw9eaa22c2020-07-01 16:21:27 -07004232TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004233 mWindow2->setWindowScale(0.5f, 0.5f);
4234
4235 // Touch Window 1
4236 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4237 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004238 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004239
4240 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004241 touchedPoints.push_back(PointF{150, 150});
4242 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004243
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004244 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004245
4246 // Move both windows
4247 touchedPoints = {{20, 20}, {175, 175}};
4248 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4249 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4250
chaviw9eaa22c2020-07-01 16:21:27 -07004251 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004252
chaviw9eaa22c2020-07-01 16:21:27 -07004253 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004254 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004255 expectedPoints.pop_back();
4256
4257 // Touch Window 2
4258 mWindow2->setWindowTransform(0, -1, 1, 0);
4259 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004260 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004261
4262 // Move both windows
4263 touchedPoints = {{20, 20}, {175, 175}};
4264 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4265 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4266
4267 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004268}
4269
4270TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4271 mWindow1->setWindowScale(0.5f, 0.5f);
4272
4273 // Touch Window 1
4274 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4275 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004276 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004277
4278 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004279 touchedPoints.push_back(PointF{150, 150});
4280 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004281
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004282 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004283
4284 // Move both windows
4285 touchedPoints = {{20, 20}, {175, 175}};
4286 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4287 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4288
chaviw9eaa22c2020-07-01 16:21:27 -07004289 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004290}
4291
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004292class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4293 virtual void SetUp() override {
4294 InputDispatcherTest::SetUp();
4295
Chris Yea209fde2020-07-22 13:54:51 -07004296 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004297 mApplication->setDispatchingTimeout(20ms);
4298 mWindow =
4299 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4300 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004301 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004302 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004303
4304 // Set focused application.
4305 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4306
4307 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004308 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004309 mWindow->consumeFocusEvent(true);
4310 }
4311
4312 virtual void TearDown() override {
4313 InputDispatcherTest::TearDown();
4314 mWindow.clear();
4315 }
4316
4317protected:
Chris Yea209fde2020-07-22 13:54:51 -07004318 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004319 sp<FakeWindowHandle> mWindow;
4320 static constexpr PointF WINDOW_LOCATION = {20, 20};
4321
4322 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004323 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004324 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4325 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004326 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004327 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4328 WINDOW_LOCATION));
4329 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004330
4331 sp<FakeWindowHandle> addSpyWindow() {
4332 sp<FakeWindowHandle> spy =
4333 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4334 spy->setTrustedOverlay(true);
4335 spy->setFocusable(false);
4336 spy->setInputFeatures(WindowInfo::Feature::SPY);
4337 spy->setDispatchingTimeout(30ms);
4338 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4339 return spy;
4340 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004341};
4342
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004343// Send a tap and respond, which should not cause an ANR.
4344TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4345 tapOnWindow();
4346 mWindow->consumeMotionDown();
4347 mWindow->consumeMotionUp();
4348 ASSERT_TRUE(mDispatcher->waitForIdle());
4349 mFakePolicy->assertNotifyAnrWasNotCalled();
4350}
4351
4352// Send a regular key and respond, which should not cause an ANR.
4353TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004354 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004355 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4356 ASSERT_TRUE(mDispatcher->waitForIdle());
4357 mFakePolicy->assertNotifyAnrWasNotCalled();
4358}
4359
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004360TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4361 mWindow->setFocusable(false);
4362 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4363 mWindow->consumeFocusEvent(false);
4364
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004365 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004366 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004367 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4368 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004369 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004370 // Key will not go to window because we have no focused window.
4371 // The 'no focused window' ANR timer should start instead.
4372
4373 // Now, the focused application goes away.
4374 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4375 // The key should get dropped and there should be no ANR.
4376
4377 ASSERT_TRUE(mDispatcher->waitForIdle());
4378 mFakePolicy->assertNotifyAnrWasNotCalled();
4379}
4380
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004381// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004382// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4383// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004384TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004385 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004386 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4387 WINDOW_LOCATION));
4388
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004389 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4390 ASSERT_TRUE(sequenceNum);
4391 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004392 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004393
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004394 mWindow->finishEvent(*sequenceNum);
4395 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4396 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004397 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004398 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004399}
4400
4401// Send a key to the app and have the app not respond right away.
4402TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4403 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004404 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004405 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4406 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004407 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004408 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004409 ASSERT_TRUE(mDispatcher->waitForIdle());
4410}
4411
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004412// We have a focused application, but no focused window
4413TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004414 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004415 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4416 mWindow->consumeFocusEvent(false);
4417
4418 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004419 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004420 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4421 WINDOW_LOCATION));
4422 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4423 mDispatcher->waitForIdle();
4424 mFakePolicy->assertNotifyAnrWasNotCalled();
4425
4426 // Once a focused event arrives, we get an ANR for this application
4427 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4428 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004429 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004430 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004431 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004432 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004433 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004434 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004435 ASSERT_TRUE(mDispatcher->waitForIdle());
4436}
4437
4438// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004439// Make sure that we don't notify policy twice about the same ANR.
4440TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004441 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004442 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4443 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004444
4445 // Once a focused event arrives, we get an ANR for this application
4446 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4447 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004448 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004449 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004450 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004451 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004452 const std::chrono::duration appTimeout =
4453 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004454 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004455
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004456 std::this_thread::sleep_for(appTimeout);
4457 // ANR should not be raised again. It is up to policy to do that if it desires.
4458 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004459
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004460 // If we now get a focused window, the ANR should stop, but the policy handles that via
4461 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004462 ASSERT_TRUE(mDispatcher->waitForIdle());
4463}
4464
4465// We have a focused application, but no focused window
4466TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004467 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004468 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4469 mWindow->consumeFocusEvent(false);
4470
4471 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004472 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004473 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004474 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4475 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004476
4477 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004478 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004479
4480 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004481 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004482 ASSERT_TRUE(mDispatcher->waitForIdle());
4483 mWindow->assertNoEvents();
4484}
4485
4486/**
4487 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4488 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4489 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4490 * the ANR mechanism should still work.
4491 *
4492 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4493 * DOWN event, while not responding on the second one.
4494 */
4495TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4496 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4497 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4498 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4499 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4500 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004501 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004502
4503 // Now send ACTION_UP, with identical timestamp
4504 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4505 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4506 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4507 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004508 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004509
4510 // We have now sent down and up. Let's consume first event and then ANR on the second.
4511 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4512 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004513 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004514}
4515
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004516// A spy window can receive an ANR
4517TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4518 sp<FakeWindowHandle> spy = addSpyWindow();
4519
4520 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4521 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4522 WINDOW_LOCATION));
4523 mWindow->consumeMotionDown();
4524
4525 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4526 ASSERT_TRUE(sequenceNum);
4527 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004528 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004529
4530 spy->finishEvent(*sequenceNum);
4531 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4532 0 /*flags*/);
4533 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004534 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004535}
4536
4537// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004538// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004539TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4540 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004541
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004542 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4543 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004544 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004545 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004546
4547 // Stuck on the ACTION_UP
4548 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004549 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004550
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004551 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004552 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004553 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4554 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004555
4556 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4557 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004558 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004559 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004560 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004561}
4562
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004563// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004564// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004565TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4566 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004567
4568 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->consumeMotionDown();
4573 // Stuck on the ACTION_UP
4574 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004575 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004576
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004577 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004578 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004579 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4580 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004581
4582 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4583 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004584 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004585 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004586 spy->assertNoEvents();
4587}
4588
4589TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4590 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4591
4592 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4593
4594 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4595 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4596 WINDOW_LOCATION));
4597
4598 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4599 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4600 ASSERT_TRUE(consumeSeq);
4601
Prabir Pradhanedd96402022-02-15 01:46:16 -08004602 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004603
4604 monitor.finishEvent(*consumeSeq);
4605 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4606
4607 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004608 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004609}
4610
4611// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4612// process events, you don't get an anr. When the window later becomes unresponsive again, you
4613// get an ANR again.
4614// 1. tap -> block on ACTION_UP -> receive ANR
4615// 2. consume all pending events (= queue becomes healthy again)
4616// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4617TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4618 tapOnWindow();
4619
4620 mWindow->consumeMotionDown();
4621 // Block on ACTION_UP
4622 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004623 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004624 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4625 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004626 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004627 mWindow->assertNoEvents();
4628
4629 tapOnWindow();
4630 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004631 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004632 mWindow->consumeMotionUp();
4633
4634 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004635 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004636 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004637 mWindow->assertNoEvents();
4638}
4639
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004640// If a connection remains unresponsive for a while, make sure policy is only notified once about
4641// it.
4642TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004643 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004644 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4645 WINDOW_LOCATION));
4646
4647 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004648 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004649 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004650 // 'notifyConnectionUnresponsive' should only be called once per connection
4651 mFakePolicy->assertNotifyAnrWasNotCalled();
4652 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004653 mWindow->consumeMotionDown();
4654 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4655 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4656 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004657 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004658 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004659 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004660}
4661
4662/**
4663 * If a window is processing a motion event, and then a key event comes in, the key event should
4664 * not to to the focused window until the motion is processed.
4665 *
4666 * Warning!!!
4667 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4668 * and the injection timeout that we specify when injecting the key.
4669 * We must have the injection timeout (10ms) be smaller than
4670 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4671 *
4672 * If that value changes, this test should also change.
4673 */
4674TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4675 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4676 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4677
4678 tapOnWindow();
4679 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4680 ASSERT_TRUE(downSequenceNum);
4681 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4682 ASSERT_TRUE(upSequenceNum);
4683 // Don't finish the events yet, and send a key
4684 // Injection will "succeed" because we will eventually give up and send the key to the focused
4685 // window even if motions are still being processed. But because the injection timeout is short,
4686 // we will receive INJECTION_TIMED_OUT as the result.
4687
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004688 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004689 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004690 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4691 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004692 // Key will not be sent to the window, yet, because the window is still processing events
4693 // and the key remains pending, waiting for the touch events to be processed
4694 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4695 ASSERT_FALSE(keySequenceNum);
4696
4697 std::this_thread::sleep_for(500ms);
4698 // if we wait long enough though, dispatcher will give up, and still send the key
4699 // to the focused window, even though we have not yet finished the motion event
4700 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4701 mWindow->finishEvent(*downSequenceNum);
4702 mWindow->finishEvent(*upSequenceNum);
4703}
4704
4705/**
4706 * If a window is processing a motion event, and then a key event comes in, the key event should
4707 * not go to the focused window until the motion is processed.
4708 * If then a new motion comes in, then the pending key event should be going to the currently
4709 * focused window right away.
4710 */
4711TEST_F(InputDispatcherSingleWindowAnr,
4712 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4713 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4714 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4715
4716 tapOnWindow();
4717 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4718 ASSERT_TRUE(downSequenceNum);
4719 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4720 ASSERT_TRUE(upSequenceNum);
4721 // Don't finish the events yet, and send a key
4722 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004723 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004724 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004725 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004726 // At this point, key is still pending, and should not be sent to the application yet.
4727 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4728 ASSERT_FALSE(keySequenceNum);
4729
4730 // Now tap down again. It should cause the pending key to go to the focused window right away.
4731 tapOnWindow();
4732 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4733 // the other events yet. We can finish events in any order.
4734 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4735 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4736 mWindow->consumeMotionDown();
4737 mWindow->consumeMotionUp();
4738 mWindow->assertNoEvents();
4739}
4740
4741class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4742 virtual void SetUp() override {
4743 InputDispatcherTest::SetUp();
4744
Chris Yea209fde2020-07-22 13:54:51 -07004745 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004746 mApplication->setDispatchingTimeout(10ms);
4747 mUnfocusedWindow =
4748 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4749 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004750 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004751 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004752
4753 mFocusedWindow =
4754 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004755 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004756 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004757
4758 // Set focused application.
4759 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004760 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004761
4762 // Expect one focus window exist in display.
4763 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004764 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004765 mFocusedWindow->consumeFocusEvent(true);
4766 }
4767
4768 virtual void TearDown() override {
4769 InputDispatcherTest::TearDown();
4770
4771 mUnfocusedWindow.clear();
4772 mFocusedWindow.clear();
4773 }
4774
4775protected:
Chris Yea209fde2020-07-22 13:54:51 -07004776 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004777 sp<FakeWindowHandle> mUnfocusedWindow;
4778 sp<FakeWindowHandle> mFocusedWindow;
4779 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4780 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4781 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4782
4783 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4784
4785 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4786
4787private:
4788 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004789 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004790 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4791 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004792 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004793 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4794 location));
4795 }
4796};
4797
4798// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4799// should be ANR'd first.
4800TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004801 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004802 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4803 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004804 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004805 mFocusedWindow->consumeMotionDown();
4806 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4807 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4808 // We consumed all events, so no ANR
4809 ASSERT_TRUE(mDispatcher->waitForIdle());
4810 mFakePolicy->assertNotifyAnrWasNotCalled();
4811
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004812 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004813 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4814 FOCUSED_WINDOW_LOCATION));
4815 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4816 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004817
4818 const std::chrono::duration timeout =
4819 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004820 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004821 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4822 // sequence to make it consistent
4823 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004824 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004825 mFocusedWindow->consumeMotionDown();
4826 // This cancel is generated because the connection was unresponsive
4827 mFocusedWindow->consumeMotionCancel();
4828 mFocusedWindow->assertNoEvents();
4829 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004830 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004831 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
4832 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004833 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004834}
4835
4836// If we have 2 windows with identical timeouts that are both unresponsive,
4837// it doesn't matter which order they should have ANR.
4838// But we should receive ANR for both.
4839TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4840 // Set the timeout for unfocused window to match the focused window
4841 mUnfocusedWindow->setDispatchingTimeout(10ms);
4842 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4843
4844 tapOnFocusedWindow();
4845 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08004846 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
4847 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
4848 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004849
4850 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004851 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4852 mFocusedWindow->getToken() == anrConnectionToken2);
4853 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4854 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004855
4856 ASSERT_TRUE(mDispatcher->waitForIdle());
4857 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004858
4859 mFocusedWindow->consumeMotionDown();
4860 mFocusedWindow->consumeMotionUp();
4861 mUnfocusedWindow->consumeMotionOutside();
4862
Prabir Pradhanedd96402022-02-15 01:46:16 -08004863 sp<IBinder> responsiveToken1, responsiveToken2;
4864 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
4865 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004866
4867 // Both applications should be marked as responsive, in any order
4868 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4869 mFocusedWindow->getToken() == responsiveToken2);
4870 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4871 mUnfocusedWindow->getToken() == responsiveToken2);
4872 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004873}
4874
4875// If a window is already not responding, the second tap on the same window should be ignored.
4876// We should also log an error to account for the dropped event (not tested here).
4877// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4878TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4879 tapOnFocusedWindow();
4880 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4881 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4882 // Receive the events, but don't respond
4883 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4884 ASSERT_TRUE(downEventSequenceNum);
4885 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4886 ASSERT_TRUE(upEventSequenceNum);
4887 const std::chrono::duration timeout =
4888 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004889 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004890
4891 // Tap once again
4892 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004893 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004894 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4895 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004896 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004897 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4898 FOCUSED_WINDOW_LOCATION));
4899 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4900 // valid touch target
4901 mUnfocusedWindow->assertNoEvents();
4902
4903 // Consume the first tap
4904 mFocusedWindow->finishEvent(*downEventSequenceNum);
4905 mFocusedWindow->finishEvent(*upEventSequenceNum);
4906 ASSERT_TRUE(mDispatcher->waitForIdle());
4907 // The second tap did not go to the focused window
4908 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004909 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08004910 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
4911 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004912 mFakePolicy->assertNotifyAnrWasNotCalled();
4913}
4914
4915// If you tap outside of all windows, there will not be ANR
4916TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004917 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004918 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4919 LOCATION_OUTSIDE_ALL_WINDOWS));
4920 ASSERT_TRUE(mDispatcher->waitForIdle());
4921 mFakePolicy->assertNotifyAnrWasNotCalled();
4922}
4923
4924// Since the focused window is paused, tapping on it should not produce any events
4925TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4926 mFocusedWindow->setPaused(true);
4927 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4928
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004929 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004930 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4931 FOCUSED_WINDOW_LOCATION));
4932
4933 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4934 ASSERT_TRUE(mDispatcher->waitForIdle());
4935 // Should not ANR because the window is paused, and touches shouldn't go to it
4936 mFakePolicy->assertNotifyAnrWasNotCalled();
4937
4938 mFocusedWindow->assertNoEvents();
4939 mUnfocusedWindow->assertNoEvents();
4940}
4941
4942/**
4943 * If a window is processing a motion event, and then a key event comes in, the key event should
4944 * not to to the focused window until the motion is processed.
4945 * If a different window becomes focused at this time, the key should go to that window instead.
4946 *
4947 * Warning!!!
4948 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4949 * and the injection timeout that we specify when injecting the key.
4950 * We must have the injection timeout (10ms) be smaller than
4951 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4952 *
4953 * If that value changes, this test should also change.
4954 */
4955TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4956 // Set a long ANR timeout to prevent it from triggering
4957 mFocusedWindow->setDispatchingTimeout(2s);
4958 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4959
4960 tapOnUnfocusedWindow();
4961 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4962 ASSERT_TRUE(downSequenceNum);
4963 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4964 ASSERT_TRUE(upSequenceNum);
4965 // Don't finish the events yet, and send a key
4966 // Injection will succeed because we will eventually give up and send the key to the focused
4967 // window even if motions are still being processed.
4968
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004969 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004970 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004971 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4972 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004973 // Key will not be sent to the window, yet, because the window is still processing events
4974 // and the key remains pending, waiting for the touch events to be processed
4975 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4976 ASSERT_FALSE(keySequenceNum);
4977
4978 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004979 mFocusedWindow->setFocusable(false);
4980 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004981 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004982 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004983
4984 // Focus events should precede the key events
4985 mUnfocusedWindow->consumeFocusEvent(true);
4986 mFocusedWindow->consumeFocusEvent(false);
4987
4988 // Finish the tap events, which should unblock dispatcher
4989 mUnfocusedWindow->finishEvent(*downSequenceNum);
4990 mUnfocusedWindow->finishEvent(*upSequenceNum);
4991
4992 // Now that all queues are cleared and no backlog in the connections, the key event
4993 // can finally go to the newly focused "mUnfocusedWindow".
4994 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4995 mFocusedWindow->assertNoEvents();
4996 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004997 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004998}
4999
5000// When the touch stream is split across 2 windows, and one of them does not respond,
5001// then ANR should be raised and the touch should be canceled for the unresponsive window.
5002// The other window should not be affected by that.
5003TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5004 // Touch Window 1
5005 NotifyMotionArgs motionArgs =
5006 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5007 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5008 mDispatcher->notifyMotion(&motionArgs);
5009 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5010 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5011
5012 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005013 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5014 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005015 mDispatcher->notifyMotion(&motionArgs);
5016
5017 const std::chrono::duration timeout =
5018 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005019 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005020
5021 mUnfocusedWindow->consumeMotionDown();
5022 mFocusedWindow->consumeMotionDown();
5023 // Focused window may or may not receive ACTION_MOVE
5024 // But it should definitely receive ACTION_CANCEL due to the ANR
5025 InputEvent* event;
5026 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5027 ASSERT_TRUE(moveOrCancelSequenceNum);
5028 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5029 ASSERT_NE(nullptr, event);
5030 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5031 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5032 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5033 mFocusedWindow->consumeMotionCancel();
5034 } else {
5035 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5036 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005037 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005038 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5039 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005040
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005041 mUnfocusedWindow->assertNoEvents();
5042 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005043 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005044}
5045
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005046/**
5047 * If we have no focused window, and a key comes in, we start the ANR timer.
5048 * The focused application should add a focused window before the timer runs out to prevent ANR.
5049 *
5050 * If the user touches another application during this time, the key should be dropped.
5051 * Next, if a new focused window comes in, without toggling the focused application,
5052 * then no ANR should occur.
5053 *
5054 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5055 * but in some cases the policy may not update the focused application.
5056 */
5057TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5058 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5059 std::make_shared<FakeApplicationHandle>();
5060 focusedApplication->setDispatchingTimeout(60ms);
5061 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5062 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5063 mFocusedWindow->setFocusable(false);
5064
5065 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5066 mFocusedWindow->consumeFocusEvent(false);
5067
5068 // Send a key. The ANR timer should start because there is no focused window.
5069 // 'focusedApplication' will get blamed if this timer completes.
5070 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005071 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005072 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005073 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5074 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005075 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005076
5077 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5078 // then the injected touches won't cause the focused event to get dropped.
5079 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5080 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5081 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5082 // For this test, it means that the key would get delivered to the window once it becomes
5083 // focused.
5084 std::this_thread::sleep_for(10ms);
5085
5086 // Touch unfocused window. This should force the pending key to get dropped.
5087 NotifyMotionArgs motionArgs =
5088 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5089 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5090 mDispatcher->notifyMotion(&motionArgs);
5091
5092 // We do not consume the motion right away, because that would require dispatcher to first
5093 // process (== drop) the key event, and by that time, ANR will be raised.
5094 // Set the focused window first.
5095 mFocusedWindow->setFocusable(true);
5096 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5097 setFocusedWindow(mFocusedWindow);
5098 mFocusedWindow->consumeFocusEvent(true);
5099 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5100 // to another application. This could be a bug / behaviour in the policy.
5101
5102 mUnfocusedWindow->consumeMotionDown();
5103
5104 ASSERT_TRUE(mDispatcher->waitForIdle());
5105 // Should not ANR because we actually have a focused window. It was just added too slowly.
5106 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5107}
5108
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005109// These tests ensure we cannot send touch events to a window that's positioned behind a window
5110// that has feature NO_INPUT_CHANNEL.
5111// Layout:
5112// Top (closest to user)
5113// mNoInputWindow (above all windows)
5114// mBottomWindow
5115// Bottom (furthest from user)
5116class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5117 virtual void SetUp() override {
5118 InputDispatcherTest::SetUp();
5119
5120 mApplication = std::make_shared<FakeApplicationHandle>();
5121 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5122 "Window without input channel", ADISPLAY_ID_DEFAULT,
5123 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5124
chaviw3277faf2021-05-19 16:45:23 -05005125 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005126 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5127 // It's perfectly valid for this window to not have an associated input channel
5128
5129 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5130 ADISPLAY_ID_DEFAULT);
5131 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5132
5133 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5134 }
5135
5136protected:
5137 std::shared_ptr<FakeApplicationHandle> mApplication;
5138 sp<FakeWindowHandle> mNoInputWindow;
5139 sp<FakeWindowHandle> mBottomWindow;
5140};
5141
5142TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5143 PointF touchedPoint = {10, 10};
5144
5145 NotifyMotionArgs motionArgs =
5146 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5147 ADISPLAY_ID_DEFAULT, {touchedPoint});
5148 mDispatcher->notifyMotion(&motionArgs);
5149
5150 mNoInputWindow->assertNoEvents();
5151 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5152 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5153 // and therefore should prevent mBottomWindow from receiving touches
5154 mBottomWindow->assertNoEvents();
5155}
5156
5157/**
5158 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5159 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5160 */
5161TEST_F(InputDispatcherMultiWindowOcclusionTests,
5162 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5163 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5164 "Window with input channel and NO_INPUT_CHANNEL",
5165 ADISPLAY_ID_DEFAULT);
5166
chaviw3277faf2021-05-19 16:45:23 -05005167 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005168 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5169 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5170
5171 PointF touchedPoint = {10, 10};
5172
5173 NotifyMotionArgs motionArgs =
5174 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5175 ADISPLAY_ID_DEFAULT, {touchedPoint});
5176 mDispatcher->notifyMotion(&motionArgs);
5177
5178 mNoInputWindow->assertNoEvents();
5179 mBottomWindow->assertNoEvents();
5180}
5181
Vishnu Nair958da932020-08-21 17:12:37 -07005182class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5183protected:
5184 std::shared_ptr<FakeApplicationHandle> mApp;
5185 sp<FakeWindowHandle> mWindow;
5186 sp<FakeWindowHandle> mMirror;
5187
5188 virtual void SetUp() override {
5189 InputDispatcherTest::SetUp();
5190 mApp = std::make_shared<FakeApplicationHandle>();
5191 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5192 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5193 mWindow->getToken());
5194 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5195 mWindow->setFocusable(true);
5196 mMirror->setFocusable(true);
5197 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5198 }
5199};
5200
5201TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5202 // Request focus on a mirrored window
5203 setFocusedWindow(mMirror);
5204
5205 // window gets focused
5206 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005207 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5208 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005209 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5210}
5211
5212// A focused & mirrored window remains focused only if the window and its mirror are both
5213// focusable.
5214TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5215 setFocusedWindow(mMirror);
5216
5217 // window gets focused
5218 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005219 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5220 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005221 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005222 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5223 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005224 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5225
5226 mMirror->setFocusable(false);
5227 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5228
5229 // window loses focus since one of the windows associated with the token in not focusable
5230 mWindow->consumeFocusEvent(false);
5231
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005232 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5233 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005234 mWindow->assertNoEvents();
5235}
5236
5237// A focused & mirrored window remains focused until the window and its mirror both become
5238// invisible.
5239TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5240 setFocusedWindow(mMirror);
5241
5242 // window gets focused
5243 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005244 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5245 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005246 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005247 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5248 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005249 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5250
5251 mMirror->setVisible(false);
5252 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5253
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005254 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5255 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005256 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005257 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5258 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005259 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5260
5261 mWindow->setVisible(false);
5262 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5263
5264 // window loses focus only after all windows associated with the token become invisible.
5265 mWindow->consumeFocusEvent(false);
5266
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005267 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5268 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005269 mWindow->assertNoEvents();
5270}
5271
5272// A focused & mirrored window remains focused until both windows are removed.
5273TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5274 setFocusedWindow(mMirror);
5275
5276 // window gets focused
5277 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005278 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5279 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005280 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005281 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5282 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005283 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5284
5285 // single window is removed but the window token remains focused
5286 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5287
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005288 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5289 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005290 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005291 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5292 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005293 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5294
5295 // Both windows are removed
5296 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5297 mWindow->consumeFocusEvent(false);
5298
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005299 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5300 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005301 mWindow->assertNoEvents();
5302}
5303
5304// Focus request can be pending until one window becomes visible.
5305TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5306 // Request focus on an invisible mirror.
5307 mWindow->setVisible(false);
5308 mMirror->setVisible(false);
5309 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5310 setFocusedWindow(mMirror);
5311
5312 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005313 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005314 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005315 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005316
5317 mMirror->setVisible(true);
5318 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5319
5320 // window gets focused
5321 mWindow->consumeFocusEvent(true);
5322 // window gets the pending key event
5323 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5324}
Prabir Pradhan99987712020-11-10 18:43:05 -08005325
5326class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5327protected:
5328 std::shared_ptr<FakeApplicationHandle> mApp;
5329 sp<FakeWindowHandle> mWindow;
5330 sp<FakeWindowHandle> mSecondWindow;
5331
5332 void SetUp() override {
5333 InputDispatcherTest::SetUp();
5334 mApp = std::make_shared<FakeApplicationHandle>();
5335 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5336 mWindow->setFocusable(true);
5337 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5338 mSecondWindow->setFocusable(true);
5339
5340 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5341 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5342
5343 setFocusedWindow(mWindow);
5344 mWindow->consumeFocusEvent(true);
5345 }
5346
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005347 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5348 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005349 mDispatcher->notifyPointerCaptureChanged(&args);
5350 }
5351
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005352 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5353 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005354 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005355 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5356 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005357 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005358 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005359 }
5360};
5361
5362TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5363 // Ensure that capture cannot be obtained for unfocused windows.
5364 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5365 mFakePolicy->assertSetPointerCaptureNotCalled();
5366 mSecondWindow->assertNoEvents();
5367
5368 // Ensure that capture can be enabled from the focus window.
5369 requestAndVerifyPointerCapture(mWindow, true);
5370
5371 // Ensure that capture cannot be disabled from a window that does not have capture.
5372 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5373 mFakePolicy->assertSetPointerCaptureNotCalled();
5374
5375 // Ensure that capture can be disabled from the window with capture.
5376 requestAndVerifyPointerCapture(mWindow, false);
5377}
5378
5379TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005380 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005381
5382 setFocusedWindow(mSecondWindow);
5383
5384 // Ensure that the capture disabled event was sent first.
5385 mWindow->consumeCaptureEvent(false);
5386 mWindow->consumeFocusEvent(false);
5387 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005388 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005389
5390 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005391 notifyPointerCaptureChanged({});
5392 notifyPointerCaptureChanged(request);
5393 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005394 mWindow->assertNoEvents();
5395 mSecondWindow->assertNoEvents();
5396 mFakePolicy->assertSetPointerCaptureNotCalled();
5397}
5398
5399TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005400 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005401
5402 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005403 notifyPointerCaptureChanged({});
5404 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005405
5406 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005407 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005408 mWindow->consumeCaptureEvent(false);
5409 mWindow->assertNoEvents();
5410}
5411
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005412TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5413 requestAndVerifyPointerCapture(mWindow, true);
5414
5415 // The first window loses focus.
5416 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005417 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005418 mWindow->consumeCaptureEvent(false);
5419
5420 // Request Pointer Capture from the second window before the notification from InputReader
5421 // arrives.
5422 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005423 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005424
5425 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005426 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005427
5428 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005429 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005430
5431 mSecondWindow->consumeFocusEvent(true);
5432 mSecondWindow->consumeCaptureEvent(true);
5433}
5434
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005435TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5436 // App repeatedly enables and disables capture.
5437 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5438 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5439 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5440 mFakePolicy->assertSetPointerCaptureCalled(false);
5441 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5442 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5443
5444 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5445 // first request is now stale, this should do nothing.
5446 notifyPointerCaptureChanged(firstRequest);
5447 mWindow->assertNoEvents();
5448
5449 // InputReader notifies that the second request was enabled.
5450 notifyPointerCaptureChanged(secondRequest);
5451 mWindow->consumeCaptureEvent(true);
5452}
5453
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005454class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5455protected:
5456 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005457
5458 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5459 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5460
5461 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5462 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5463
5464 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5465 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5466 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5467 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5468 MAXIMUM_OBSCURING_OPACITY);
5469
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005470 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005471 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005472 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005473
5474 sp<FakeWindowHandle> mTouchWindow;
5475
5476 virtual void SetUp() override {
5477 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005478 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005479 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5480 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5481 }
5482
5483 virtual void TearDown() override {
5484 InputDispatcherTest::TearDown();
5485 mTouchWindow.clear();
5486 }
5487
chaviw3277faf2021-05-19 16:45:23 -05005488 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5489 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005490 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005491 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005492 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005493 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005494 return window;
5495 }
5496
5497 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5498 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5499 sp<FakeWindowHandle> window =
5500 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5501 // Generate an arbitrary PID based on the UID
5502 window->setOwnerInfo(1777 + (uid % 10000), uid);
5503 return window;
5504 }
5505
5506 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5507 NotifyMotionArgs args =
5508 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5509 ADISPLAY_ID_DEFAULT, points);
5510 mDispatcher->notifyMotion(&args);
5511 }
5512};
5513
5514TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005515 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005516 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005517 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005518
5519 touch();
5520
5521 mTouchWindow->assertNoEvents();
5522}
5523
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005524TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005525 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5526 const sp<FakeWindowHandle>& w =
5527 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5528 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5529
5530 touch();
5531
5532 mTouchWindow->assertNoEvents();
5533}
5534
5535TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005536 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5537 const sp<FakeWindowHandle>& w =
5538 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5539 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5540
5541 touch();
5542
5543 w->assertNoEvents();
5544}
5545
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005546TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005547 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5548 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005549
5550 touch();
5551
5552 mTouchWindow->consumeAnyMotionDown();
5553}
5554
5555TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005556 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005557 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005558 w->setFrame(Rect(0, 0, 50, 50));
5559 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005560
5561 touch({PointF{100, 100}});
5562
5563 mTouchWindow->consumeAnyMotionDown();
5564}
5565
5566TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005567 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005568 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005569 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5570
5571 touch();
5572
5573 mTouchWindow->consumeAnyMotionDown();
5574}
5575
5576TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5577 const sp<FakeWindowHandle>& w =
5578 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5579 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005580
5581 touch();
5582
5583 mTouchWindow->consumeAnyMotionDown();
5584}
5585
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005586TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5587 const sp<FakeWindowHandle>& w =
5588 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5589 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5590
5591 touch();
5592
5593 w->assertNoEvents();
5594}
5595
5596/**
5597 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5598 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5599 * window, the occluding window will still receive ACTION_OUTSIDE event.
5600 */
5601TEST_F(InputDispatcherUntrustedTouchesTest,
5602 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5603 const sp<FakeWindowHandle>& w =
5604 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005605 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005606 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5607
5608 touch();
5609
5610 w->consumeMotionOutside();
5611}
5612
5613TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5614 const sp<FakeWindowHandle>& w =
5615 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005616 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005617 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5618
5619 touch();
5620
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005621 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005622}
5623
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005624TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005625 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005626 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5627 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005628 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5629
5630 touch();
5631
5632 mTouchWindow->consumeAnyMotionDown();
5633}
5634
5635TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5636 const sp<FakeWindowHandle>& w =
5637 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5638 MAXIMUM_OBSCURING_OPACITY);
5639 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005640
5641 touch();
5642
5643 mTouchWindow->consumeAnyMotionDown();
5644}
5645
5646TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005647 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005648 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5649 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5651
5652 touch();
5653
5654 mTouchWindow->assertNoEvents();
5655}
5656
5657TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5658 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5659 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005660 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5661 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005662 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005663 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5664 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005665 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5666
5667 touch();
5668
5669 mTouchWindow->assertNoEvents();
5670}
5671
5672TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5673 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5674 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005675 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5676 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005677 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005678 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5679 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005680 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5681
5682 touch();
5683
5684 mTouchWindow->consumeAnyMotionDown();
5685}
5686
5687TEST_F(InputDispatcherUntrustedTouchesTest,
5688 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5689 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005690 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5691 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005692 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005693 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5694 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005695 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5696
5697 touch();
5698
5699 mTouchWindow->consumeAnyMotionDown();
5700}
5701
5702TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5703 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005704 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5705 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005706 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005707 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5708 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005709 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005710
5711 touch();
5712
5713 mTouchWindow->assertNoEvents();
5714}
5715
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005716TEST_F(InputDispatcherUntrustedTouchesTest,
5717 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5718 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005719 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5720 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005721 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005722 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5723 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005724 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5725
5726 touch();
5727
5728 mTouchWindow->assertNoEvents();
5729}
5730
5731TEST_F(InputDispatcherUntrustedTouchesTest,
5732 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5733 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005734 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5735 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005736 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005737 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5738 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005739 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5740
5741 touch();
5742
5743 mTouchWindow->consumeAnyMotionDown();
5744}
5745
5746TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5747 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005748 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5749 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005750 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5751
5752 touch();
5753
5754 mTouchWindow->consumeAnyMotionDown();
5755}
5756
5757TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5758 const sp<FakeWindowHandle>& w =
5759 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5760 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5761
5762 touch();
5763
5764 mTouchWindow->consumeAnyMotionDown();
5765}
5766
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005767TEST_F(InputDispatcherUntrustedTouchesTest,
5768 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5769 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5770 const sp<FakeWindowHandle>& w =
5771 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5772 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5773
5774 touch();
5775
5776 mTouchWindow->assertNoEvents();
5777}
5778
5779TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5780 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5781 const sp<FakeWindowHandle>& w =
5782 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5783 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5784
5785 touch();
5786
5787 mTouchWindow->consumeAnyMotionDown();
5788}
5789
5790TEST_F(InputDispatcherUntrustedTouchesTest,
5791 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5792 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5793 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005794 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5795 OPACITY_ABOVE_THRESHOLD);
5796 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5797
5798 touch();
5799
5800 mTouchWindow->consumeAnyMotionDown();
5801}
5802
5803TEST_F(InputDispatcherUntrustedTouchesTest,
5804 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5805 const sp<FakeWindowHandle>& w1 =
5806 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5807 OPACITY_BELOW_THRESHOLD);
5808 const sp<FakeWindowHandle>& w2 =
5809 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5810 OPACITY_BELOW_THRESHOLD);
5811 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5812
5813 touch();
5814
5815 mTouchWindow->assertNoEvents();
5816}
5817
5818/**
5819 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5820 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5821 * (which alone would result in allowing touches) does not affect the blocking behavior.
5822 */
5823TEST_F(InputDispatcherUntrustedTouchesTest,
5824 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5825 const sp<FakeWindowHandle>& wB =
5826 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5827 OPACITY_BELOW_THRESHOLD);
5828 const sp<FakeWindowHandle>& wC =
5829 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5830 OPACITY_BELOW_THRESHOLD);
5831 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5832
5833 touch();
5834
5835 mTouchWindow->assertNoEvents();
5836}
5837
5838/**
5839 * This test is testing that a window from a different UID but with same application token doesn't
5840 * block the touch. Apps can share the application token for close UI collaboration for example.
5841 */
5842TEST_F(InputDispatcherUntrustedTouchesTest,
5843 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5844 const sp<FakeWindowHandle>& w =
5845 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5846 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005847 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5848
5849 touch();
5850
5851 mTouchWindow->consumeAnyMotionDown();
5852}
5853
arthurhungb89ccb02020-12-30 16:19:01 +08005854class InputDispatcherDragTests : public InputDispatcherTest {
5855protected:
5856 std::shared_ptr<FakeApplicationHandle> mApp;
5857 sp<FakeWindowHandle> mWindow;
5858 sp<FakeWindowHandle> mSecondWindow;
5859 sp<FakeWindowHandle> mDragWindow;
5860
5861 void SetUp() override {
5862 InputDispatcherTest::SetUp();
5863 mApp = std::make_shared<FakeApplicationHandle>();
5864 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5865 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005866
5867 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5868 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005869
5870 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5871 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5872 }
5873
5874 // Start performing drag, we will create a drag window and transfer touch to it.
5875 void performDrag() {
5876 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5877 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5878 {50, 50}))
5879 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5880
5881 // Window should receive motion event.
5882 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5883
5884 // The drag window covers the entire display
5885 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5886 mDispatcher->setInputWindows(
5887 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5888
5889 // Transfer touch focus to the drag window
5890 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5891 true /* isDragDrop */);
5892 mWindow->consumeMotionCancel();
5893 mDragWindow->consumeMotionDown();
5894 }
arthurhung6d4bed92021-03-17 11:59:33 +08005895
5896 // Start performing drag, we will create a drag window and transfer touch to it.
5897 void performStylusDrag() {
5898 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5899 injectMotionEvent(mDispatcher,
5900 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5901 AINPUT_SOURCE_STYLUS)
5902 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5903 .pointer(PointerBuilder(0,
5904 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5905 .x(50)
5906 .y(50))
5907 .build()));
5908 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5909
5910 // The drag window covers the entire display
5911 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5912 mDispatcher->setInputWindows(
5913 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5914
5915 // Transfer touch focus to the drag window
5916 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5917 true /* isDragDrop */);
5918 mWindow->consumeMotionCancel();
5919 mDragWindow->consumeMotionDown();
5920 }
arthurhungb89ccb02020-12-30 16:19:01 +08005921};
5922
5923TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5924 performDrag();
5925
5926 // Move on window.
5927 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5928 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5929 ADISPLAY_ID_DEFAULT, {50, 50}))
5930 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5931 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5932 mWindow->consumeDragEvent(false, 50, 50);
5933 mSecondWindow->assertNoEvents();
5934
5935 // Move to another window.
5936 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5937 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5938 ADISPLAY_ID_DEFAULT, {150, 50}))
5939 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5940 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5941 mWindow->consumeDragEvent(true, 150, 50);
5942 mSecondWindow->consumeDragEvent(false, 50, 50);
5943
5944 // Move back to original window.
5945 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5946 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5947 ADISPLAY_ID_DEFAULT, {50, 50}))
5948 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5949 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5950 mWindow->consumeDragEvent(false, 50, 50);
5951 mSecondWindow->consumeDragEvent(true, -50, 50);
5952
5953 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5954 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5955 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5956 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5957 mWindow->assertNoEvents();
5958 mSecondWindow->assertNoEvents();
5959}
5960
arthurhungf452d0b2021-01-06 00:19:52 +08005961TEST_F(InputDispatcherDragTests, DragAndDrop) {
5962 performDrag();
5963
5964 // Move on window.
5965 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5966 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5967 ADISPLAY_ID_DEFAULT, {50, 50}))
5968 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5969 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5970 mWindow->consumeDragEvent(false, 50, 50);
5971 mSecondWindow->assertNoEvents();
5972
5973 // Move to another window.
5974 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5975 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5976 ADISPLAY_ID_DEFAULT, {150, 50}))
5977 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5978 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5979 mWindow->consumeDragEvent(true, 150, 50);
5980 mSecondWindow->consumeDragEvent(false, 50, 50);
5981
5982 // drop to another window.
5983 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5984 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5985 {150, 50}))
5986 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5987 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5988 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5989 mWindow->assertNoEvents();
5990 mSecondWindow->assertNoEvents();
5991}
5992
arthurhung6d4bed92021-03-17 11:59:33 +08005993TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5994 performStylusDrag();
5995
5996 // Move on window and keep button pressed.
5997 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5998 injectMotionEvent(mDispatcher,
5999 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6000 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6001 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6002 .x(50)
6003 .y(50))
6004 .build()))
6005 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6006 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6007 mWindow->consumeDragEvent(false, 50, 50);
6008 mSecondWindow->assertNoEvents();
6009
6010 // Move to another window and release button, expect to drop item.
6011 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6012 injectMotionEvent(mDispatcher,
6013 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6014 .buttonState(0)
6015 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6016 .x(150)
6017 .y(50))
6018 .build()))
6019 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6020 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6021 mWindow->assertNoEvents();
6022 mSecondWindow->assertNoEvents();
6023 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6024
6025 // nothing to the window.
6026 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6027 injectMotionEvent(mDispatcher,
6028 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6029 .buttonState(0)
6030 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6031 .x(150)
6032 .y(50))
6033 .build()))
6034 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6035 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6036 mWindow->assertNoEvents();
6037 mSecondWindow->assertNoEvents();
6038}
6039
Arthur Hung6d0571e2021-04-09 20:18:16 +08006040TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6041 performDrag();
6042
6043 // Set second window invisible.
6044 mSecondWindow->setVisible(false);
6045 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6046
6047 // Move on window.
6048 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6049 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6050 ADISPLAY_ID_DEFAULT, {50, 50}))
6051 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6052 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6053 mWindow->consumeDragEvent(false, 50, 50);
6054 mSecondWindow->assertNoEvents();
6055
6056 // Move to another window.
6057 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6058 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6059 ADISPLAY_ID_DEFAULT, {150, 50}))
6060 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6061 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6062 mWindow->consumeDragEvent(true, 150, 50);
6063 mSecondWindow->assertNoEvents();
6064
6065 // drop to another window.
6066 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6067 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6068 {150, 50}))
6069 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6070 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6071 mFakePolicy->assertDropTargetEquals(nullptr);
6072 mWindow->assertNoEvents();
6073 mSecondWindow->assertNoEvents();
6074}
6075
Vishnu Nair062a8672021-09-03 16:07:44 -07006076class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6077
6078TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6079 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6080 sp<FakeWindowHandle> window =
6081 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6082 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
6083 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6084 window->setFocusable(true);
6085 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6086 setFocusedWindow(window);
6087 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6088
6089 // With the flag set, window should not get any input
6090 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6091 mDispatcher->notifyKey(&keyArgs);
6092 window->assertNoEvents();
6093
6094 NotifyMotionArgs motionArgs =
6095 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6096 ADISPLAY_ID_DEFAULT);
6097 mDispatcher->notifyMotion(&motionArgs);
6098 window->assertNoEvents();
6099
6100 // With the flag cleared, the window should get input
6101 window->setInputFeatures({});
6102 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6103
6104 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6105 mDispatcher->notifyKey(&keyArgs);
6106 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6107
6108 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6109 ADISPLAY_ID_DEFAULT);
6110 mDispatcher->notifyMotion(&motionArgs);
6111 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6112 window->assertNoEvents();
6113}
6114
6115TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6116 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6117 std::make_shared<FakeApplicationHandle>();
6118 sp<FakeWindowHandle> obscuringWindow =
6119 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6120 ADISPLAY_ID_DEFAULT);
6121 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6122 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006123 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006124 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6125 sp<FakeWindowHandle> window =
6126 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6127 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6128 window->setOwnerInfo(222, 222);
6129 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6130 window->setFocusable(true);
6131 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6132 setFocusedWindow(window);
6133 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6134
6135 // With the flag set, window should not get any input
6136 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6137 mDispatcher->notifyKey(&keyArgs);
6138 window->assertNoEvents();
6139
6140 NotifyMotionArgs motionArgs =
6141 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6142 ADISPLAY_ID_DEFAULT);
6143 mDispatcher->notifyMotion(&motionArgs);
6144 window->assertNoEvents();
6145
6146 // With the flag cleared, the window should get input
6147 window->setInputFeatures({});
6148 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6149
6150 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6151 mDispatcher->notifyKey(&keyArgs);
6152 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6153
6154 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6155 ADISPLAY_ID_DEFAULT);
6156 mDispatcher->notifyMotion(&motionArgs);
6157 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6158 window->assertNoEvents();
6159}
6160
6161TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6162 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6163 std::make_shared<FakeApplicationHandle>();
6164 sp<FakeWindowHandle> obscuringWindow =
6165 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6166 ADISPLAY_ID_DEFAULT);
6167 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6168 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006169 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006170 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6171 sp<FakeWindowHandle> window =
6172 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6173 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6174 window->setOwnerInfo(222, 222);
6175 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6176 window->setFocusable(true);
6177 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6178 setFocusedWindow(window);
6179 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6180
6181 // With the flag set, window should not get any input
6182 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6183 mDispatcher->notifyKey(&keyArgs);
6184 window->assertNoEvents();
6185
6186 NotifyMotionArgs motionArgs =
6187 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6188 ADISPLAY_ID_DEFAULT);
6189 mDispatcher->notifyMotion(&motionArgs);
6190 window->assertNoEvents();
6191
6192 // When the window is no longer obscured because it went on top, it should get input
6193 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6194
6195 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6196 mDispatcher->notifyKey(&keyArgs);
6197 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6198
6199 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6200 ADISPLAY_ID_DEFAULT);
6201 mDispatcher->notifyMotion(&motionArgs);
6202 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6203 window->assertNoEvents();
6204}
6205
Antonio Kantekf16f2832021-09-28 04:39:20 +00006206class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6207protected:
6208 std::shared_ptr<FakeApplicationHandle> mApp;
6209 sp<FakeWindowHandle> mWindow;
6210 sp<FakeWindowHandle> mSecondWindow;
6211
6212 void SetUp() override {
6213 InputDispatcherTest::SetUp();
6214
6215 mApp = std::make_shared<FakeApplicationHandle>();
6216 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6217 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006218 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006219 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6220 mSecondWindow->setFocusable(true);
6221
6222 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6223 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006224 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006225
6226 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
6227 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, INJECTOR_PID,
6228 INJECTOR_UID, /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006229 }
6230
Antonio Kantekea47acb2021-12-23 12:41:25 -08006231 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006232 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006233 mWindow->consumeTouchModeEvent(inTouchMode);
6234 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6235 }
6236};
6237
Antonio Kantek26defcf2022-02-08 01:12:27 +00006238TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006239 const WindowInfo& windowInfo = *mWindow->getInfo();
6240 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6241 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006242}
6243
Antonio Kantek26defcf2022-02-08 01:12:27 +00006244TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6245 const WindowInfo& windowInfo = *mWindow->getInfo();
6246 int32_t ownerPid = windowInfo.ownerPid;
6247 int32_t ownerUid = windowInfo.ownerUid;
6248 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6249 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6250 ownerUid, /* hasPermission */ false));
6251 mWindow->assertNoEvents();
6252 mSecondWindow->assertNoEvents();
6253}
6254
6255TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6256 const WindowInfo& windowInfo = *mWindow->getInfo();
6257 int32_t ownerPid = windowInfo.ownerPid;
6258 int32_t ownerUid = windowInfo.ownerUid;
6259 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6260 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6261 /* hasPermission */ true);
6262}
6263
Antonio Kantekf16f2832021-09-28 04:39:20 +00006264TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006265 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006266 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6267 windowInfo.ownerPid, windowInfo.ownerUid,
6268 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006269 mWindow->assertNoEvents();
6270 mSecondWindow->assertNoEvents();
6271}
6272
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006273class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6274public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006275 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006276 std::shared_ptr<FakeApplicationHandle> application =
6277 std::make_shared<FakeApplicationHandle>();
6278 std::string name = "Fake Spy ";
6279 name += std::to_string(mSpyCount++);
6280 sp<FakeWindowHandle> spy =
6281 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
6282 spy->setInputFeatures(WindowInfo::Feature::SPY);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006283 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006284 return spy;
6285 }
6286
6287 sp<FakeWindowHandle> createForeground() {
6288 std::shared_ptr<FakeApplicationHandle> application =
6289 std::make_shared<FakeApplicationHandle>();
6290 sp<FakeWindowHandle> window =
6291 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006292 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006293 return window;
6294 }
6295
6296private:
6297 int mSpyCount{0};
6298};
6299
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006300using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006301/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006302 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6303 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006304TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6305 ScopedSilentDeath _silentDeath;
6306
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006307 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006308 spy->setTrustedOverlay(false);
6309 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6310 ".* not a trusted overlay");
6311}
6312
6313/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006314 * Input injection into a display with a spy window but no foreground windows should succeed.
6315 */
6316TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006317 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006318 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6319
6320 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6321 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6322 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6323 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6324}
6325
6326/**
6327 * Verify the order in which different input windows receive events. The touched foreground window
6328 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6329 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6330 * receive events before ones belows it.
6331 *
6332 * Here, we set up a scenario with four windows in the following Z order from the top:
6333 * spy1, spy2, window, spy3.
6334 * We then inject an event and verify that the foreground "window" receives it first, followed by
6335 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6336 * window.
6337 */
6338TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6339 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006340 auto spy1 = createSpy();
6341 auto spy2 = createSpy();
6342 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006343 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6344 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6345 const size_t numChannels = channels.size();
6346
Michael Wright8e9a8562022-02-09 13:44:29 +00006347 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006348 if (!epollFd.ok()) {
6349 FAIL() << "Failed to create epoll fd";
6350 }
6351
6352 for (size_t i = 0; i < numChannels; i++) {
6353 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6354 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6355 FAIL() << "Failed to add fd to epoll";
6356 }
6357 }
6358
6359 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6360 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6361 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6362
6363 std::vector<size_t> eventOrder;
6364 std::vector<struct epoll_event> events(numChannels);
6365 for (;;) {
6366 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6367 (100ms).count());
6368 if (nFds < 0) {
6369 FAIL() << "Failed to call epoll_wait";
6370 }
6371 if (nFds == 0) {
6372 break; // epoll_wait timed out
6373 }
6374 for (int i = 0; i < nFds; i++) {
6375 ASSERT_EQ(EPOLLIN, events[i].events);
6376 eventOrder.push_back(events[i].data.u64);
6377 channels[i]->consumeMotionDown();
6378 }
6379 }
6380
6381 // Verify the order in which the events were received.
6382 EXPECT_EQ(3u, eventOrder.size());
6383 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6384 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6385 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6386}
6387
6388/**
6389 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6390 */
6391TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6392 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006393 auto spy = createSpy();
6394 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006395 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6396
6397 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6398 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6399 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6400 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6401 spy->assertNoEvents();
6402}
6403
6404/**
6405 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6406 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6407 * to the window.
6408 */
6409TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6410 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006411 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006412 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6413 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6414
6415 // Inject an event outside the spy window's touchable region.
6416 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6417 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6418 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6419 window->consumeMotionDown();
6420 spy->assertNoEvents();
6421 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6422 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6423 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6424 window->consumeMotionUp();
6425 spy->assertNoEvents();
6426
6427 // Inject an event inside the spy window's touchable region.
6428 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6429 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6430 {5, 10}))
6431 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6432 window->consumeMotionDown();
6433 spy->consumeMotionDown();
6434}
6435
6436/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006437 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006438 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006439 */
6440TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6441 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006442 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006443 auto spy = createSpy();
6444 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006445 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006446 spy->setFrame(Rect{0, 0, 20, 20});
6447 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6448
6449 // Inject an event outside the spy window's frame and touchable region.
6450 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006451 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6452 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006453 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6454 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006455 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006456}
6457
6458/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006459 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6460 * any other windows - including other spy windows - will also be cancelled.
6461 */
6462TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6463 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006464 auto spy1 = createSpy();
6465 auto spy2 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006466 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6467
6468 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6469 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6470 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6471 window->consumeMotionDown();
6472 spy1->consumeMotionDown();
6473 spy2->consumeMotionDown();
6474
6475 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006476 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006477 spy2->assertNoEvents();
6478 spy1->consumeMotionCancel();
6479 window->consumeMotionCancel();
6480
6481 // The rest of the gesture should only be sent to the second spy window.
6482 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6483 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6484 ADISPLAY_ID_DEFAULT))
6485 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6486 spy2->consumeMotionMove();
6487 spy1->assertNoEvents();
6488 window->assertNoEvents();
6489}
6490
6491/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006492 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
6493 * in the middle of the gesture.
6494 */
6495TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
6496 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006497 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006498 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6499
6500 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6501 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6502 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6503 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6504 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6505
6506 window->releaseChannel();
6507
6508 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6509
6510 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6511 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6512 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6513 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6514}
6515
6516/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006517 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
6518 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006519 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006520TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006521 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006522 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006523
6524 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6525
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006526 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006527 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6528 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6529 {100, 200}))
6530 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006531 spy->consumeMotionDown();
6532 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006533
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006534 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006535 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006536 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006537
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006538 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006539 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006540 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006541 .displayId(ADISPLAY_ID_DEFAULT)
6542 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6543 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6544 .x(100)
6545 .y(200))
6546 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6547 .build();
6548 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6549 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6550 InputEventInjectionSync::WAIT_FOR_RESULT))
6551 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6552
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006553 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6554
6555 // Third finger goes down outside all windows, so injection should fail.
6556 const MotionEvent thirdFingerDownEvent =
6557 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6558 (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6559 AINPUT_SOURCE_TOUCHSCREEN)
6560 .displayId(ADISPLAY_ID_DEFAULT)
6561 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6562 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6563 .x(100)
6564 .y(200))
6565 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6566 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
6567 .build();
6568 ASSERT_EQ(InputEventInjectionResult::FAILED,
6569 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
6570 InputEventInjectionSync::WAIT_FOR_RESULT))
6571 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6572
6573 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006574 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006575}
6576
6577/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006578 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6579 * pointers that are down within its bounds.
6580 */
6581TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6582 auto windowLeft = createForeground();
6583 windowLeft->setFrame({0, 0, 100, 200});
6584 auto windowRight = createForeground();
6585 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006586 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006587 spy->setFrame({0, 0, 200, 200});
6588 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6589
6590 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6591 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6592 {50, 50}))
6593 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6594 windowLeft->consumeMotionDown();
6595 spy->consumeMotionDown();
6596
6597 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006598 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006599 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6600 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6601 .pointer(
6602 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6603 .build();
6604 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6605 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6606 InputEventInjectionSync::WAIT_FOR_RESULT))
6607 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6608 windowRight->consumeMotionDown();
6609 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6610}
6611
6612/**
6613 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6614 * the spy should receive the second pointer with ACTION_DOWN.
6615 */
6616TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6617 auto window = createForeground();
6618 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006619 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006620 spyRight->setFrame({100, 0, 200, 200});
6621 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6622
6623 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6624 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6625 {50, 50}))
6626 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6627 window->consumeMotionDown();
6628 spyRight->assertNoEvents();
6629
6630 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006631 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006632 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6633 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6634 .pointer(
6635 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6636 .build();
6637 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6638 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6639 InputEventInjectionSync::WAIT_FOR_RESULT))
6640 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6641 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6642 spyRight->consumeMotionDown();
6643}
6644
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006645/**
6646 * The spy window should not be able to affect whether or not touches are split. Only the foreground
6647 * windows should be allowed to control split touch.
6648 */
6649TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006650 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006651 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006652 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006653 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006654
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006655 auto window = createForeground();
6656 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006657
6658 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6659
6660 // First finger down, no window touched.
6661 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6662 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6663 {100, 200}))
6664 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6665 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6666 window->assertNoEvents();
6667
6668 // Second finger down on window, the window should receive touch down.
6669 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006670 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006671 .displayId(ADISPLAY_ID_DEFAULT)
6672 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6673 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6674 .x(100)
6675 .y(200))
6676 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6677 .build();
6678 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6679 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6680 InputEventInjectionSync::WAIT_FOR_RESULT))
6681 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6682
6683 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6684 spy->consumeMotionPointerDown(1 /* pointerIndex */);
6685}
6686
6687/**
6688 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
6689 * do not receive key events.
6690 */
6691TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006692 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006693 spy->setFocusable(false);
6694
6695 auto window = createForeground();
6696 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6697 setFocusedWindow(window);
6698 window->consumeFocusEvent(true);
6699
6700 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6701 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6702 window->consumeKeyDown(ADISPLAY_ID_NONE);
6703
6704 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6705 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6706 window->consumeKeyUp(ADISPLAY_ID_NONE);
6707
6708 spy->assertNoEvents();
6709}
6710
Prabir Pradhand65552b2021-10-07 11:23:50 -07006711class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6712public:
6713 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6714 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6715 std::make_shared<FakeApplicationHandle>();
6716 sp<FakeWindowHandle> overlay =
6717 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6718 ADISPLAY_ID_DEFAULT);
6719 overlay->setFocusable(false);
6720 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006721 overlay->setTouchable(false);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006722 overlay->setInputFeatures(WindowInfo::Feature::INTERCEPTS_STYLUS);
6723 overlay->setTrustedOverlay(true);
6724
6725 std::shared_ptr<FakeApplicationHandle> application =
6726 std::make_shared<FakeApplicationHandle>();
6727 sp<FakeWindowHandle> window =
6728 new FakeWindowHandle(application, mDispatcher, "Application window",
6729 ADISPLAY_ID_DEFAULT);
6730 window->setFocusable(true);
6731 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006732
6733 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6734 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6735 setFocusedWindow(window);
6736 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6737 return {std::move(overlay), std::move(window)};
6738 }
6739
6740 void sendFingerEvent(int32_t action) {
6741 NotifyMotionArgs motionArgs =
6742 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6743 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6744 mDispatcher->notifyMotion(&motionArgs);
6745 }
6746
6747 void sendStylusEvent(int32_t action) {
6748 NotifyMotionArgs motionArgs =
6749 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6750 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6751 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6752 mDispatcher->notifyMotion(&motionArgs);
6753 }
6754};
6755
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006756using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
6757
6758TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
6759 ScopedSilentDeath _silentDeath;
6760
Prabir Pradhand65552b2021-10-07 11:23:50 -07006761 auto [overlay, window] = setupStylusOverlayScenario();
6762 overlay->setTrustedOverlay(false);
6763 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6764 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6765 ".* not a trusted overlay");
6766}
6767
6768TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6769 auto [overlay, window] = setupStylusOverlayScenario();
6770 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6771
6772 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6773 overlay->consumeMotionDown();
6774 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6775 overlay->consumeMotionUp();
6776
6777 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6778 window->consumeMotionDown();
6779 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6780 window->consumeMotionUp();
6781
6782 overlay->assertNoEvents();
6783 window->assertNoEvents();
6784}
6785
6786TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6787 auto [overlay, window] = setupStylusOverlayScenario();
6788 overlay->setInputFeatures(overlay->getInfo()->inputFeatures | WindowInfo::Feature::SPY);
6789 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6790
6791 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6792 overlay->consumeMotionDown();
6793 window->consumeMotionDown();
6794 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6795 overlay->consumeMotionUp();
6796 window->consumeMotionUp();
6797
6798 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6799 window->consumeMotionDown();
6800 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6801 window->consumeMotionUp();
6802
6803 overlay->assertNoEvents();
6804 window->assertNoEvents();
6805}
6806
Garfield Tane84e6f92019-08-29 17:28:41 -07006807} // namespace android::inputdispatcher