blob: 9633932e75ebdd0ac4271e2fed3c019943f2988a [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
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080068static constexpr std::chrono::duration STALE_EVENT_TIMEOUT = 1000ms;
69
chaviwd1c23182019-12-20 18:44:56 -080070struct PointF {
71 float x;
72 float y;
73};
Michael Wrightd02c5b62014-02-10 15:10:22 -080074
Gang Wang342c9272020-01-13 13:15:04 -050075/**
76 * Return a DOWN key event with KEYCODE_A.
77 */
78static KeyEvent getTestKeyEvent() {
79 KeyEvent event;
80
Garfield Tanfbe732e2020-01-24 11:26:14 -080081 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
82 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
83 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050084 return event;
85}
86
Siarhei Vishniakouca205502021-07-16 21:31:58 +000087static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
88 ASSERT_EQ(expectedAction, receivedAction)
89 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
90 << MotionEvent::actionToString(receivedAction);
91}
92
Michael Wrightd02c5b62014-02-10 15:10:22 -080093// --- FakeInputDispatcherPolicy ---
94
95class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
96 InputDispatcherConfiguration mConfig;
97
Prabir Pradhanedd96402022-02-15 01:46:16 -080098 using AnrResult = std::pair<sp<IBinder>, int32_t /*pid*/>;
99
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000101 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102
103public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000104 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +0800105
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800106 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700107 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
108 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
109 EXPECT_EQ(event.getDisplayId(), args.displayId);
110
111 const auto& keyEvent = static_cast<const KeyEvent&>(event);
112 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
113 EXPECT_EQ(keyEvent.getAction(), args.action);
114 });
Jackal Guof9696682018-10-05 12:23:23 +0800115 }
116
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700117 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
118 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
119 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
120 EXPECT_EQ(event.getDisplayId(), args.displayId);
121
122 const auto& motionEvent = static_cast<const MotionEvent&>(event);
123 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
124 EXPECT_EQ(motionEvent.getAction(), args.action);
125 EXPECT_EQ(motionEvent.getX(0), point.x);
126 EXPECT_EQ(motionEvent.getY(0), point.y);
127 EXPECT_EQ(motionEvent.getRawX(0), point.x);
128 EXPECT_EQ(motionEvent.getRawY(0), point.y);
129 });
Jackal Guof9696682018-10-05 12:23:23 +0800130 }
131
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700132 void assertFilterInputEventWasNotCalled() {
133 std::scoped_lock lock(mLock);
134 ASSERT_EQ(nullptr, mFilteredEvent);
135 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800136
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800137 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700138 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800139 ASSERT_TRUE(mConfigurationChangedTime)
140 << "Timed out waiting for configuration changed call";
141 ASSERT_EQ(*mConfigurationChangedTime, when);
142 mConfigurationChangedTime = std::nullopt;
143 }
144
145 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700146 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800147 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800148 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800149 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
150 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
151 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
152 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
153 mLastNotifySwitch = std::nullopt;
154 }
155
chaviwfd6d3512019-03-25 13:23:49 -0700156 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700157 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800158 ASSERT_EQ(touchedToken, mOnPointerDownToken);
159 mOnPointerDownToken.clear();
160 }
161
162 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700163 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800164 ASSERT_TRUE(mOnPointerDownToken == nullptr)
165 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700166 }
167
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700168 // This function must be called soon after the expected ANR timer starts,
169 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500170 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700171 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500172 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800173 std::unique_lock lock(mLock);
174 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500175 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800176 ASSERT_NO_FATAL_FAILURE(
177 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500178 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700179 }
180
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000181 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800182 const sp<WindowInfoHandle>& window) {
183 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
184 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
185 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500186 }
187
Prabir Pradhanedd96402022-02-15 01:46:16 -0800188 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
189 const sp<IBinder>& expectedToken,
190 int32_t expectedPid) {
191 std::unique_lock lock(mLock);
192 android::base::ScopedLockAssertion assumeLocked(mLock);
193 AnrResult result;
194 ASSERT_NO_FATAL_FAILURE(result =
195 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
196 const auto& [token, pid] = result;
197 ASSERT_EQ(expectedToken, token);
198 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500199 }
200
Prabir Pradhanedd96402022-02-15 01:46:16 -0800201 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000202 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500203 std::unique_lock lock(mLock);
204 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800205 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
206 const auto& [token, _] = result;
207 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000208 }
209
Prabir Pradhanedd96402022-02-15 01:46:16 -0800210 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
211 int32_t expectedPid) {
212 std::unique_lock lock(mLock);
213 android::base::ScopedLockAssertion assumeLocked(mLock);
214 AnrResult result;
215 ASSERT_NO_FATAL_FAILURE(
216 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
217 const auto& [token, pid] = result;
218 ASSERT_EQ(expectedToken, token);
219 ASSERT_EQ(expectedPid, pid);
220 }
221
222 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000223 sp<IBinder> getResponsiveWindowToken() {
224 std::unique_lock lock(mLock);
225 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800226 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
227 const auto& [token, _] = result;
228 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700229 }
230
231 void assertNotifyAnrWasNotCalled() {
232 std::scoped_lock lock(mLock);
233 ASSERT_TRUE(mAnrApplications.empty());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800234 ASSERT_TRUE(mAnrWindows.empty());
235 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500236 << "ANR was not called, but please also consume the 'connection is responsive' "
237 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700238 }
239
Garfield Tan1c7bc862020-01-28 13:24:04 -0800240 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
241 mConfig.keyRepeatTimeout = timeout;
242 mConfig.keyRepeatDelay = delay;
243 }
244
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000245 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800246 std::unique_lock lock(mLock);
247 base::ScopedLockAssertion assumeLocked(mLock);
248
249 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
250 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000251 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800252 enabled;
253 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000254 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
255 << ") to be called.";
256 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800257 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000258 auto request = *mPointerCaptureRequest;
259 mPointerCaptureRequest.reset();
260 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800261 }
262
263 void assertSetPointerCaptureNotCalled() {
264 std::unique_lock lock(mLock);
265 base::ScopedLockAssertion assumeLocked(mLock);
266
267 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000268 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800269 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000270 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800271 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000272 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800273 }
274
arthurhungf452d0b2021-01-06 00:19:52 +0800275 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
276 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800277 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800278 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800279 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800280 }
281
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800282 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
283 std::unique_lock lock(mLock);
284 base::ScopedLockAssertion assumeLocked(mLock);
285 std::optional<sp<IBinder>> receivedToken =
286 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
287 mNotifyInputChannelBroken);
288 ASSERT_TRUE(receivedToken.has_value());
289 ASSERT_EQ(token, *receivedToken);
290 }
291
Michael Wrightd02c5b62014-02-10 15:10:22 -0800292private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700293 std::mutex mLock;
294 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
295 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
296 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
297 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800298
Prabir Pradhan99987712020-11-10 18:43:05 -0800299 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000300
301 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800302
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700303 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700304 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800305 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
306 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700307 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800308 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
309 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700310
arthurhungf452d0b2021-01-06 00:19:52 +0800311 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800312 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800313
Prabir Pradhanedd96402022-02-15 01:46:16 -0800314 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
315 // for a specific container to become non-empty. When the container is non-empty, return the
316 // first entry from the container and erase it.
317 template <class T>
318 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
319 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
320 // If there is an ANR, Dispatcher won't be idle because there are still events
321 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
322 // before checking if ANR was called.
323 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
324 // to provide it some time to act. 100ms seems reasonable.
325 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
326 const std::chrono::time_point start = std::chrono::steady_clock::now();
327 std::optional<T> token =
328 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
329 if (!token.has_value()) {
330 ADD_FAILURE() << "Did not receive the ANR callback";
331 return {};
332 }
333
334 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
335 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
336 // the dispatcher started counting before this function was called
337 if (std::chrono::abs(timeout - waited) > 100ms) {
338 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
339 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
340 << "ms, but waited "
341 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
342 << "ms instead";
343 }
344 return *token;
345 }
346
347 template <class T>
348 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
349 std::queue<T>& storage,
350 std::unique_lock<std::mutex>& lock,
351 std::condition_variable& condition)
352 REQUIRES(mLock) {
353 condition.wait_for(lock, timeout,
354 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
355 if (storage.empty()) {
356 ADD_FAILURE() << "Did not receive the expected callback";
357 return std::nullopt;
358 }
359 T item = storage.front();
360 storage.pop();
361 return std::make_optional(item);
362 }
363
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600364 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700365 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800366 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800367 }
368
Prabir Pradhanedd96402022-02-15 01:46:16 -0800369 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
370 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700371 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800372 ASSERT_TRUE(pid.has_value());
373 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700374 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500375 }
376
Prabir Pradhanedd96402022-02-15 01:46:16 -0800377 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
378 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500379 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800380 ASSERT_TRUE(pid.has_value());
381 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500382 mNotifyAnr.notify_all();
383 }
384
385 void notifyNoFocusedWindowAnr(
386 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
387 std::scoped_lock lock(mLock);
388 mAnrApplications.push(applicationHandle);
389 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800390 }
391
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800392 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
393 std::scoped_lock lock(mLock);
394 mBrokenInputChannels.push(connectionToken);
395 mNotifyInputChannelBroken.notify_all();
396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800397
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600398 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700399
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600400 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700401 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
402 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
403 const std::vector<float>& values) override {}
404
405 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
406 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000407
Chris Yefb552902021-02-03 17:18:37 -0800408 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
409
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600410 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411 *outConfig = mConfig;
412 }
413
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600414 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700415 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800416 switch (inputEvent->getType()) {
417 case AINPUT_EVENT_TYPE_KEY: {
418 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800419 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800420 break;
421 }
422
423 case AINPUT_EVENT_TYPE_MOTION: {
424 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800425 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800426 break;
427 }
428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800429 return true;
430 }
431
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600432 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800433
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600434 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800435
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600436 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437 return 0;
438 }
439
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600440 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800441 return false;
442 }
443
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600444 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
445 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700446 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800447 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
448 * essentially a passthrough for notifySwitch.
449 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800450 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800451 }
452
Sean Stoutb4e0a592021-02-23 07:34:53 -0800453 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800454
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800455 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
456 return pid == INJECTOR_PID && uid == INJECTOR_UID;
457 }
Jackal Guof9696682018-10-05 12:23:23 +0800458
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600459 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700460 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700461 mOnPointerDownToken = newToken;
462 }
463
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000464 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800465 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000466 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800467 mPointerCaptureChangedCondition.notify_all();
468 }
469
arthurhungf452d0b2021-01-06 00:19:52 +0800470 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
471 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800472 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800473 mDropTargetWindowToken = token;
474 }
475
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700476 void assertFilterInputEventWasCalledInternal(
477 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700478 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800479 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700480 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800481 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800483};
484
Michael Wrightd02c5b62014-02-10 15:10:22 -0800485// --- InputDispatcherTest ---
486
487class InputDispatcherTest : public testing::Test {
488protected:
489 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700490 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800491
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000492 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800494 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800495 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000496 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700497 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800498 }
499
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000500 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700501 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700503 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800504 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700505
506 /**
507 * Used for debugging when writing the test
508 */
509 void dumpDispatcherState() {
510 std::string dump;
511 mDispatcher->dump(dump);
512 std::stringstream ss(dump);
513 std::string to;
514
515 while (std::getline(ss, to, '\n')) {
516 ALOGE("%s", to.c_str());
517 }
518 }
Vishnu Nair958da932020-08-21 17:12:37 -0700519
chaviw3277faf2021-05-19 16:45:23 -0500520 void setFocusedWindow(const sp<WindowInfoHandle>& window,
521 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700522 FocusRequest request;
523 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000524 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700525 if (focusedWindow) {
526 request.focusedToken = focusedWindow->getToken();
527 }
528 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
529 request.displayId = window->getInfo()->displayId;
530 mDispatcher->setFocusedWindow(request);
531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532};
533
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
535 KeyEvent event;
536
537 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800538 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
539 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600540 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
541 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800542 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700543 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800544 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545 << "Should reject key events with undefined action.";
546
547 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800548 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
549 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600550 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800551 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700552 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800553 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554 << "Should reject key events with ACTION_MULTIPLE.";
555}
556
557TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
558 MotionEvent event;
559 PointerProperties pointerProperties[MAX_POINTERS + 1];
560 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800561 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 pointerProperties[i].clear();
563 pointerProperties[i].id = i;
564 pointerCoords[i].clear();
565 }
566
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800567 // Some constants commonly used below
568 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
569 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
570 constexpr int32_t metaState = AMETA_NONE;
571 constexpr MotionClassification classification = MotionClassification::NONE;
572
chaviw9eaa22c2020-07-01 16:21:27 -0700573 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800574 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800575 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700576 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
577 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700578 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
579 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700580 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800581 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700582 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800583 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800584 << "Should reject motion events with undefined action.";
585
586 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800587 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800588 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
589 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
590 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
591 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500592 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800593 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700594 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800595 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596 << "Should reject motion events with pointer down index too large.";
597
Garfield Tanfbe732e2020-01-24 11:26:14 -0800598 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700599 AMOTION_EVENT_ACTION_POINTER_DOWN |
600 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700601 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
602 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700603 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500604 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800605 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700606 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800607 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800608 << "Should reject motion events with pointer down index too small.";
609
610 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800611 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800612 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
613 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
614 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
615 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500616 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800617 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700618 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800619 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800620 << "Should reject motion events with pointer up index too large.";
621
Garfield Tanfbe732e2020-01-24 11:26:14 -0800622 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700623 AMOTION_EVENT_ACTION_POINTER_UP |
624 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700625 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
626 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700627 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500628 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800629 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700630 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800631 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 << "Should reject motion events with pointer up index too small.";
633
634 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800635 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
636 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700637 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700638 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
639 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700640 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800641 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700642 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800643 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800644 << "Should reject motion events with 0 pointers.";
645
Garfield Tanfbe732e2020-01-24 11:26:14 -0800646 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
647 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700648 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700649 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
650 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700651 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800652 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700653 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800654 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655 << "Should reject motion events with more than MAX_POINTERS pointers.";
656
657 // Rejects motion events with invalid pointer ids.
658 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800659 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
660 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700661 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700662 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
663 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700664 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800665 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700666 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800667 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 << "Should reject motion events with pointer ids less than 0.";
669
670 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800671 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
672 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700673 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700674 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
675 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700676 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800677 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700678 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800679 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
681
682 // Rejects motion events with duplicate pointer ids.
683 pointerProperties[0].id = 1;
684 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800685 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
686 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700687 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700688 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
689 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700690 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800691 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700692 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800693 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800694 << "Should reject motion events with duplicate pointer ids.";
695}
696
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800697/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
698
699TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
700 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800701 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800702 mDispatcher->notifyConfigurationChanged(&args);
703 ASSERT_TRUE(mDispatcher->waitForIdle());
704
705 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
706}
707
708TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800709 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
710 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800711 mDispatcher->notifySwitch(&args);
712
713 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
714 args.policyFlags |= POLICY_FLAG_TRUSTED;
715 mFakePolicy->assertNotifySwitchWasCalled(args);
716}
717
Arthur Hungb92218b2018-08-14 12:00:21 +0800718// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700719static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700720// Default input dispatching timeout if there is no focused application or paused window
721// from which to determine an appropriate dispatching timeout.
722static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
723 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
724 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800725
726class FakeApplicationHandle : public InputApplicationHandle {
727public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700728 FakeApplicationHandle() {
729 mInfo.name = "Fake Application";
730 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500731 mInfo.dispatchingTimeoutMillis =
732 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700733 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800734 virtual ~FakeApplicationHandle() {}
735
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000736 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700737
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500738 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
739 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700740 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800741};
742
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800743class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800744public:
Garfield Tan15601662020-09-22 15:32:38 -0700745 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800746 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700747 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800748 }
749
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800750 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700751 InputEvent* event;
752 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
753 if (!consumeSeq) {
754 return nullptr;
755 }
756 finishEvent(*consumeSeq);
757 return event;
758 }
759
760 /**
761 * Receive an event without acknowledging it.
762 * Return the sequence number that could later be used to send finished signal.
763 */
764 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800765 uint32_t consumeSeq;
766 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800767
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800768 std::chrono::time_point start = std::chrono::steady_clock::now();
769 status_t status = WOULD_BLOCK;
770 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800771 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800772 &event);
773 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
774 if (elapsed > 100ms) {
775 break;
776 }
777 }
778
779 if (status == WOULD_BLOCK) {
780 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700781 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800782 }
783
784 if (status != OK) {
785 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700786 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800787 }
788 if (event == nullptr) {
789 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700790 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800791 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700792 if (outEvent != nullptr) {
793 *outEvent = event;
794 }
795 return consumeSeq;
796 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800797
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700798 /**
799 * To be used together with "receiveEvent" to complete the consumption of an event.
800 */
801 void finishEvent(uint32_t consumeSeq) {
802 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
803 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800804 }
805
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000806 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
807 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
808 ASSERT_EQ(OK, status);
809 }
810
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000811 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
812 std::optional<int32_t> expectedDisplayId,
813 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800814 InputEvent* event = consume();
815
816 ASSERT_NE(nullptr, event) << mName.c_str()
817 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800818 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700819 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800820 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800821
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000822 if (expectedDisplayId.has_value()) {
823 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
824 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800825
Tiger Huang8664f8c2018-10-11 19:14:35 +0800826 switch (expectedEventType) {
827 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800828 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
829 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000830 if (expectedFlags.has_value()) {
831 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
832 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800833 break;
834 }
835 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800836 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000837 assertMotionAction(expectedAction, motionEvent.getAction());
838
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000839 if (expectedFlags.has_value()) {
840 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
841 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800842 break;
843 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100844 case AINPUT_EVENT_TYPE_FOCUS: {
845 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
846 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800847 case AINPUT_EVENT_TYPE_CAPTURE: {
848 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
849 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000850 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
851 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
852 }
arthurhungb89ccb02020-12-30 16:19:01 +0800853 case AINPUT_EVENT_TYPE_DRAG: {
854 FAIL() << "Use 'consumeDragEvent' for DRAG events";
855 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800856 default: {
857 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
858 }
859 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800860 }
861
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100862 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
863 InputEvent* event = consume();
864 ASSERT_NE(nullptr, event) << mName.c_str()
865 << ": consumer should have returned non-NULL event.";
866 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
867 << "Got " << inputEventTypeToString(event->getType())
868 << " event instead of FOCUS event";
869
870 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
871 << mName.c_str() << ": event displayId should always be NONE.";
872
873 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
874 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100875 }
876
Prabir Pradhan99987712020-11-10 18:43:05 -0800877 void consumeCaptureEvent(bool hasCapture) {
878 const InputEvent* event = consume();
879 ASSERT_NE(nullptr, event) << mName.c_str()
880 << ": consumer should have returned non-NULL event.";
881 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
882 << "Got " << inputEventTypeToString(event->getType())
883 << " event instead of CAPTURE event";
884
885 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
886 << mName.c_str() << ": event displayId should always be NONE.";
887
888 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
889 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
890 }
891
arthurhungb89ccb02020-12-30 16:19:01 +0800892 void consumeDragEvent(bool isExiting, float x, float y) {
893 const InputEvent* event = consume();
894 ASSERT_NE(nullptr, event) << mName.c_str()
895 << ": consumer should have returned non-NULL event.";
896 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
897 << "Got " << inputEventTypeToString(event->getType())
898 << " event instead of DRAG event";
899
900 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
901 << mName.c_str() << ": event displayId should always be NONE.";
902
903 const auto& dragEvent = static_cast<const DragEvent&>(*event);
904 EXPECT_EQ(isExiting, dragEvent.isExiting());
905 EXPECT_EQ(x, dragEvent.getX());
906 EXPECT_EQ(y, dragEvent.getY());
907 }
908
Antonio Kantekf16f2832021-09-28 04:39:20 +0000909 void consumeTouchModeEvent(bool inTouchMode) {
910 const InputEvent* event = consume();
911 ASSERT_NE(nullptr, event) << mName.c_str()
912 << ": consumer should have returned non-NULL event.";
913 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
914 << "Got " << inputEventTypeToString(event->getType())
915 << " event instead of TOUCH_MODE event";
916
917 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
918 << mName.c_str() << ": event displayId should always be NONE.";
919 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
920 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
921 }
922
chaviwd1c23182019-12-20 18:44:56 -0800923 void assertNoEvents() {
924 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700925 if (event == nullptr) {
926 return;
927 }
928 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
929 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
930 ADD_FAILURE() << "Received key event "
931 << KeyEvent::actionToString(keyEvent.getAction());
932 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
933 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
934 ADD_FAILURE() << "Received motion event "
935 << MotionEvent::actionToString(motionEvent.getAction());
936 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
937 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
938 ADD_FAILURE() << "Received focus event, hasFocus = "
939 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800940 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
941 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
942 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
943 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000944 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
945 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
946 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
947 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700948 }
949 FAIL() << mName.c_str()
950 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800951 }
952
953 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
954
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800955 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
956
chaviwd1c23182019-12-20 18:44:56 -0800957protected:
958 std::unique_ptr<InputConsumer> mConsumer;
959 PreallocatedInputEventFactory mEventFactory;
960
961 std::string mName;
962};
963
chaviw3277faf2021-05-19 16:45:23 -0500964class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800965public:
966 static const int32_t WIDTH = 600;
967 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800968
Chris Yea209fde2020-07-22 13:54:51 -0700969 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700970 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500971 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800972 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500973 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700974 base::Result<std::unique_ptr<InputChannel>> channel =
975 dispatcher->createInputChannel(name);
976 token = (*channel)->getConnectionToken();
977 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800978 }
979
980 inputApplicationHandle->updateInfo();
981 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
982
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500983 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700984 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800985 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500986 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000987 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800988 mInfo.frameLeft = 0;
989 mInfo.frameTop = 0;
990 mInfo.frameRight = WIDTH;
991 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700992 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800993 mInfo.globalScaleFactor = 1.0;
994 mInfo.touchableRegion.clear();
995 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
chaviwd1c23182019-12-20 18:44:56 -0800996 mInfo.ownerPid = INJECTOR_PID;
997 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800998 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -0800999 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001000 }
1001
Arthur Hungabbb9d82021-09-01 14:52:30 +00001002 sp<FakeWindowHandle> clone(
1003 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001004 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001005 sp<FakeWindowHandle> handle =
1006 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1007 displayId, mInfo.token);
1008 return handle;
1009 }
1010
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001011 void setTouchable(bool touchable) {
1012 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1013 }
chaviwd1c23182019-12-20 18:44:56 -08001014
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001015 void setFocusable(bool focusable) {
1016 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1017 }
1018
1019 void setVisible(bool visible) {
1020 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1021 }
Vishnu Nair958da932020-08-21 17:12:37 -07001022
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001023 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001024 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001025 }
1026
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001027 void setPaused(bool paused) {
1028 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1029 }
1030
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001031 void setPreventSplitting(bool preventSplitting) {
1032 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001033 }
1034
1035 void setSlippery(bool slippery) {
1036 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1037 }
1038
1039 void setWatchOutsideTouch(bool watchOutside) {
1040 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1041 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001042
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001043 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1044
1045 void setInterceptsStylus(bool interceptsStylus) {
1046 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1047 }
1048
1049 void setDropInput(bool dropInput) {
1050 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1051 }
1052
1053 void setDropInputIfObscured(bool dropInputIfObscured) {
1054 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1055 }
1056
1057 void setNoInputChannel(bool noInputChannel) {
1058 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1059 }
1060
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001061 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1062
chaviw3277faf2021-05-19 16:45:23 -05001063 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001064
Bernardo Rufino7393d172021-02-26 13:56:11 +00001065 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1066
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001067 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001068 mInfo.frameLeft = frame.left;
1069 mInfo.frameTop = frame.top;
1070 mInfo.frameRight = frame.right;
1071 mInfo.frameBottom = frame.bottom;
1072 mInfo.touchableRegion.clear();
1073 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001074
1075 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1076 ui::Transform translate;
1077 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1078 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001079 }
1080
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001081 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1082
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001083 void setIsWallpaper(bool isWallpaper) {
1084 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1085 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001086
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001087 void setDupTouchToWallpaper(bool hasWallpaper) {
1088 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1089 }
chaviwd1c23182019-12-20 18:44:56 -08001090
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001091 void setTrustedOverlay(bool trustedOverlay) {
1092 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1093 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001094
chaviw9eaa22c2020-07-01 16:21:27 -07001095 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1096 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1097 }
1098
1099 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001100
yunho.shinf4a80b82020-11-16 21:13:57 +09001101 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1102
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001103 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1104 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1105 expectedFlags);
1106 }
1107
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001108 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1109 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1110 }
1111
Svet Ganov5d3bc372020-01-26 23:11:07 -08001112 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001113 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001114 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1115 expectedFlags);
1116 }
1117
1118 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001119 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001120 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1121 expectedFlags);
1122 }
1123
1124 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001125 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001126 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1127 }
1128
1129 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1130 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001131 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1132 expectedFlags);
1133 }
1134
Svet Ganov5d3bc372020-01-26 23:11:07 -08001135 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001136 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1137 int32_t expectedFlags = 0) {
1138 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1139 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001140 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1141 }
1142
1143 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001144 int32_t expectedFlags = 0) {
1145 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1146 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001147 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1148 }
1149
1150 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001151 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001152 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1153 expectedFlags);
1154 }
1155
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001156 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1157 int32_t expectedFlags = 0) {
1158 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1159 expectedFlags);
1160 }
1161
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001162 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1163 int32_t expectedFlags = 0) {
1164 InputEvent* event = consume();
1165 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1166 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1167 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1168 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1169 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1170 }
1171
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001172 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1173 ASSERT_NE(mInputReceiver, nullptr)
1174 << "Cannot consume events from a window with no receiver";
1175 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1176 }
1177
Prabir Pradhan99987712020-11-10 18:43:05 -08001178 void consumeCaptureEvent(bool hasCapture) {
1179 ASSERT_NE(mInputReceiver, nullptr)
1180 << "Cannot consume events from a window with no receiver";
1181 mInputReceiver->consumeCaptureEvent(hasCapture);
1182 }
1183
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001184 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1185 std::optional<int32_t> expectedDisplayId,
1186 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001187 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1188 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1189 expectedFlags);
1190 }
1191
arthurhungb89ccb02020-12-30 16:19:01 +08001192 void consumeDragEvent(bool isExiting, float x, float y) {
1193 mInputReceiver->consumeDragEvent(isExiting, x, y);
1194 }
1195
Antonio Kantekf16f2832021-09-28 04:39:20 +00001196 void consumeTouchModeEvent(bool inTouchMode) {
1197 ASSERT_NE(mInputReceiver, nullptr)
1198 << "Cannot consume events from a window with no receiver";
1199 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1200 }
1201
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001202 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001203 if (mInputReceiver == nullptr) {
1204 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1205 return std::nullopt;
1206 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001207 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001208 }
1209
1210 void finishEvent(uint32_t sequenceNum) {
1211 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1212 mInputReceiver->finishEvent(sequenceNum);
1213 }
1214
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001215 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1216 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1217 mInputReceiver->sendTimeline(inputEventId, timeline);
1218 }
1219
chaviwaf87b3e2019-10-01 16:59:28 -07001220 InputEvent* consume() {
1221 if (mInputReceiver == nullptr) {
1222 return nullptr;
1223 }
1224 return mInputReceiver->consume();
1225 }
1226
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001227 MotionEvent* consumeMotion() {
1228 InputEvent* event = consume();
1229 if (event == nullptr) {
1230 ADD_FAILURE() << "Consume failed : no event";
1231 return nullptr;
1232 }
1233 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1234 ADD_FAILURE() << "Instead of motion event, got "
1235 << inputEventTypeToString(event->getType());
1236 return nullptr;
1237 }
1238 return static_cast<MotionEvent*>(event);
1239 }
1240
Arthur Hungb92218b2018-08-14 12:00:21 +08001241 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001242 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001243 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001244 return; // Can't receive events if the window does not have input channel
1245 }
1246 ASSERT_NE(nullptr, mInputReceiver)
1247 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001248 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001249 }
1250
chaviwaf87b3e2019-10-01 16:59:28 -07001251 sp<IBinder> getToken() { return mInfo.token; }
1252
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001253 const std::string& getName() { return mName; }
1254
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001255 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1256 mInfo.ownerPid = ownerPid;
1257 mInfo.ownerUid = ownerUid;
1258 }
1259
Prabir Pradhanedd96402022-02-15 01:46:16 -08001260 int32_t getPid() const { return mInfo.ownerPid; }
1261
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001262 void destroyReceiver() { mInputReceiver = nullptr; }
1263
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001264 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1265
chaviwd1c23182019-12-20 18:44:56 -08001266private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001267 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001268 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001269 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001270};
1271
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001272std::atomic<int32_t> FakeWindowHandle::sId{1};
1273
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001274static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001275 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001276 int32_t displayId = ADISPLAY_ID_NONE,
1277 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001278 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1279 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001280 KeyEvent event;
1281 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1282
1283 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001284 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001285 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1286 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001287
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001288 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1289 if (!allowKeyRepeat) {
1290 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1291 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001292 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001293 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001294 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001295}
1296
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001297static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001298 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001299 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1300}
1301
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001302// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1303// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1304// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001305static InputEventInjectionResult injectKeyDownNoRepeat(
1306 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001307 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1308 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1309 /* allowKeyRepeat */ false);
1310}
1311
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001312static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001313 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001314 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1315}
1316
Garfield Tandf26e862020-07-01 20:18:19 -07001317class PointerBuilder {
1318public:
1319 PointerBuilder(int32_t id, int32_t toolType) {
1320 mProperties.clear();
1321 mProperties.id = id;
1322 mProperties.toolType = toolType;
1323 mCoords.clear();
1324 }
1325
1326 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1327
1328 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1329
1330 PointerBuilder& axis(int32_t axis, float value) {
1331 mCoords.setAxisValue(axis, value);
1332 return *this;
1333 }
1334
1335 PointerProperties buildProperties() const { return mProperties; }
1336
1337 PointerCoords buildCoords() const { return mCoords; }
1338
1339private:
1340 PointerProperties mProperties;
1341 PointerCoords mCoords;
1342};
1343
1344class MotionEventBuilder {
1345public:
1346 MotionEventBuilder(int32_t action, int32_t source) {
1347 mAction = action;
1348 mSource = source;
1349 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1350 }
1351
1352 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1353 mEventTime = eventTime;
1354 return *this;
1355 }
1356
1357 MotionEventBuilder& displayId(int32_t displayId) {
1358 mDisplayId = displayId;
1359 return *this;
1360 }
1361
1362 MotionEventBuilder& actionButton(int32_t actionButton) {
1363 mActionButton = actionButton;
1364 return *this;
1365 }
1366
arthurhung6d4bed92021-03-17 11:59:33 +08001367 MotionEventBuilder& buttonState(int32_t buttonState) {
1368 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001369 return *this;
1370 }
1371
1372 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1373 mRawXCursorPosition = rawXCursorPosition;
1374 return *this;
1375 }
1376
1377 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1378 mRawYCursorPosition = rawYCursorPosition;
1379 return *this;
1380 }
1381
1382 MotionEventBuilder& pointer(PointerBuilder pointer) {
1383 mPointers.push_back(pointer);
1384 return *this;
1385 }
1386
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001387 MotionEventBuilder& addFlag(uint32_t flags) {
1388 mFlags |= flags;
1389 return *this;
1390 }
1391
Garfield Tandf26e862020-07-01 20:18:19 -07001392 MotionEvent build() {
1393 std::vector<PointerProperties> pointerProperties;
1394 std::vector<PointerCoords> pointerCoords;
1395 for (const PointerBuilder& pointer : mPointers) {
1396 pointerProperties.push_back(pointer.buildProperties());
1397 pointerCoords.push_back(pointer.buildCoords());
1398 }
1399
1400 // Set mouse cursor position for the most common cases to avoid boilerplate.
1401 if (mSource == AINPUT_SOURCE_MOUSE &&
1402 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1403 mPointers.size() == 1) {
1404 mRawXCursorPosition = pointerCoords[0].getX();
1405 mRawYCursorPosition = pointerCoords[0].getY();
1406 }
1407
1408 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001409 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001410 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001411 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001412 mButtonState, MotionClassification::NONE, identityTransform,
1413 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001414 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1415 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001416
1417 return event;
1418 }
1419
1420private:
1421 int32_t mAction;
1422 int32_t mSource;
1423 nsecs_t mEventTime;
1424 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1425 int32_t mActionButton{0};
1426 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001427 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001428 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1429 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1430
1431 std::vector<PointerBuilder> mPointers;
1432};
1433
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001434static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001435 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001436 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001437 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001438 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1439 injectionTimeout,
1440 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1441}
1442
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001443static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001444 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001445 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001446 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001447 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1448 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001449 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001450 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001451 MotionEvent event = MotionEventBuilder(action, source)
1452 .displayId(displayId)
1453 .eventTime(eventTime)
1454 .rawXCursorPosition(cursorPosition.x)
1455 .rawYCursorPosition(cursorPosition.y)
1456 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1457 .x(position.x)
1458 .y(position.y))
1459 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001460
1461 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001462 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001463}
1464
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001465static InputEventInjectionResult injectMotionDown(
1466 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1467 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001468 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001469}
1470
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001471static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001472 int32_t source, int32_t displayId,
1473 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001474 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001475}
1476
Jackal Guof9696682018-10-05 12:23:23 +08001477static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1478 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1479 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001480 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1481 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1482 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001483
1484 return args;
1485}
1486
chaviwd1c23182019-12-20 18:44:56 -08001487static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1488 const std::vector<PointF>& points) {
1489 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001490 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1491 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1492 }
1493
chaviwd1c23182019-12-20 18:44:56 -08001494 PointerProperties pointerProperties[pointerCount];
1495 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001496
chaviwd1c23182019-12-20 18:44:56 -08001497 for (size_t i = 0; i < pointerCount; i++) {
1498 pointerProperties[i].clear();
1499 pointerProperties[i].id = i;
1500 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001501
chaviwd1c23182019-12-20 18:44:56 -08001502 pointerCoords[i].clear();
1503 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1504 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1505 }
Jackal Guof9696682018-10-05 12:23:23 +08001506
1507 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1508 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001509 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001510 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1511 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001512 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1513 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001514 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1515 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001516
1517 return args;
1518}
1519
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001520static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1521 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1522}
1523
chaviwd1c23182019-12-20 18:44:56 -08001524static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1525 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1526}
1527
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001528static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1529 const PointerCaptureRequest& request) {
1530 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001531}
1532
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001533/**
1534 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1535 * broken channel.
1536 */
1537TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1538 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1539 sp<FakeWindowHandle> window =
1540 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1541 ADISPLAY_ID_DEFAULT);
1542
1543 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1544
1545 // Window closes its channel, but the window remains.
1546 window->destroyReceiver();
1547 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1548}
1549
Arthur Hungb92218b2018-08-14 12:00:21 +08001550TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001551 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001552 sp<FakeWindowHandle> window =
1553 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001554
Arthur Hung72d8dc32020-03-28 00:48:39 +00001555 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001556 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1557 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1558 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001559
1560 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001561 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001562}
1563
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001564TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1565 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1566 sp<FakeWindowHandle> window =
1567 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1568
1569 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1570 // Inject a MotionEvent to an unknown display.
1571 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1572 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1573 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1574
1575 // Window should receive motion event.
1576 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1577}
1578
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001579/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001580 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001581 * This test serves as a sanity check for the next test, where setInputWindows is
1582 * called twice.
1583 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001584TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001585 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001586 sp<FakeWindowHandle> window =
1587 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1588 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001589
1590 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001591 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001592 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1593 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001594 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001595
1596 // Window should receive motion event.
1597 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1598}
1599
1600/**
1601 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001602 */
1603TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001604 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001605 sp<FakeWindowHandle> window =
1606 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1607 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001608
1609 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1610 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001611 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001612 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1613 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001614 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001615
1616 // Window should receive motion event.
1617 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1618}
1619
Arthur Hungb92218b2018-08-14 12:00:21 +08001620// The foreground window should receive the first touch down event.
1621TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001622 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001623 sp<FakeWindowHandle> windowTop =
1624 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1625 sp<FakeWindowHandle> windowSecond =
1626 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001627
Arthur Hung72d8dc32020-03-28 00:48:39 +00001628 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001629 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1630 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1631 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001632
1633 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001634 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001635 windowSecond->assertNoEvents();
1636}
1637
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001638/**
1639 * Two windows: A top window, and a wallpaper behind the window.
1640 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1641 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001642 * 1. foregroundWindow <-- dup touch to wallpaper
1643 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001644 */
1645TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1646 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1647 sp<FakeWindowHandle> foregroundWindow =
1648 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001649 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001650 sp<FakeWindowHandle> wallpaperWindow =
1651 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001652 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001653 constexpr int expectedWallpaperFlags =
1654 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1655
1656 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1657 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1658 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1659 {100, 200}))
1660 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1661
1662 // Both foreground window and its wallpaper should receive the touch down
1663 foregroundWindow->consumeMotionDown();
1664 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1665
1666 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1667 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1668 ADISPLAY_ID_DEFAULT, {110, 200}))
1669 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1670
1671 foregroundWindow->consumeMotionMove();
1672 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1673
1674 // Now the foreground window goes away, but the wallpaper stays
1675 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1676 foregroundWindow->consumeMotionCancel();
1677 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1678 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1679}
1680
1681/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001682 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1683 * with the following differences:
1684 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1685 * clean up the connection.
1686 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1687 * Ensure that there's no crash in the dispatcher.
1688 */
1689TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1690 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1691 sp<FakeWindowHandle> foregroundWindow =
1692 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001693 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001694 sp<FakeWindowHandle> wallpaperWindow =
1695 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001696 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001697 constexpr int expectedWallpaperFlags =
1698 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1699
1700 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1701 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1702 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1703 {100, 200}))
1704 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1705
1706 // Both foreground window and its wallpaper should receive the touch down
1707 foregroundWindow->consumeMotionDown();
1708 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1709
1710 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1711 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1712 ADISPLAY_ID_DEFAULT, {110, 200}))
1713 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1714
1715 foregroundWindow->consumeMotionMove();
1716 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1717
1718 // Wallpaper closes its channel, but the window remains.
1719 wallpaperWindow->destroyReceiver();
1720 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1721
1722 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1723 // is no longer valid.
1724 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1725 foregroundWindow->consumeMotionCancel();
1726}
1727
1728/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001729 * A single window that receives touch (on top), and a wallpaper window underneath it.
1730 * The top window gets a multitouch gesture.
1731 * Ensure that wallpaper gets the same gesture.
1732 */
1733TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1734 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1735 sp<FakeWindowHandle> window =
1736 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001737 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001738
1739 sp<FakeWindowHandle> wallpaperWindow =
1740 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001741 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001742 constexpr int expectedWallpaperFlags =
1743 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1744
1745 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1746
1747 // Touch down on top window
1748 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1749 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1750 {100, 100}))
1751 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1752
1753 // Both top window and its wallpaper should receive the touch down
1754 window->consumeMotionDown();
1755 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1756
1757 // Second finger down on the top window
1758 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001759 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001760 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1761 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1762 .x(100)
1763 .y(100))
1764 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1765 .x(150)
1766 .y(150))
1767 .build();
1768 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1769 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1770 InputEventInjectionSync::WAIT_FOR_RESULT))
1771 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1772
1773 window->consumeMotionPointerDown(1 /* pointerIndex */);
1774 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1775 expectedWallpaperFlags);
1776 window->assertNoEvents();
1777 wallpaperWindow->assertNoEvents();
1778}
1779
1780/**
1781 * Two windows: a window on the left and window on the right.
1782 * A third window, wallpaper, is behind both windows, and spans both top windows.
1783 * The first touch down goes to the left window. A second pointer touches down on the right window.
1784 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1785 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1786 * ACTION_POINTER_DOWN(1).
1787 */
1788TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1789 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1790 sp<FakeWindowHandle> leftWindow =
1791 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1792 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001793 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001794
1795 sp<FakeWindowHandle> rightWindow =
1796 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1797 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001798 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001799
1800 sp<FakeWindowHandle> wallpaperWindow =
1801 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1802 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001803 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001804 constexpr int expectedWallpaperFlags =
1805 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1806
1807 mDispatcher->setInputWindows(
1808 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1809
1810 // Touch down on left window
1811 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1812 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1813 {100, 100}))
1814 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1815
1816 // Both foreground window and its wallpaper should receive the touch down
1817 leftWindow->consumeMotionDown();
1818 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1819
1820 // Second finger down on the right window
1821 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001822 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001823 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1824 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1825 .x(100)
1826 .y(100))
1827 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1828 .x(300)
1829 .y(100))
1830 .build();
1831 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1832 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1833 InputEventInjectionSync::WAIT_FOR_RESULT))
1834 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1835
1836 leftWindow->consumeMotionMove();
1837 // Since the touch is split, right window gets ACTION_DOWN
1838 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1839 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1840 expectedWallpaperFlags);
1841
1842 // Now, leftWindow, which received the first finger, disappears.
1843 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1844 leftWindow->consumeMotionCancel();
1845 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1846 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1847
1848 // The pointer that's still down on the right window moves, and goes to the right window only.
1849 // As far as the dispatcher's concerned though, both pointers are still present.
1850 const MotionEvent secondFingerMoveEvent =
1851 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1852 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1853 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1854 .x(100)
1855 .y(100))
1856 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1857 .x(310)
1858 .y(110))
1859 .build();
1860 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1861 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1862 InputEventInjectionSync::WAIT_FOR_RESULT));
1863 rightWindow->consumeMotionMove();
1864
1865 leftWindow->assertNoEvents();
1866 rightWindow->assertNoEvents();
1867 wallpaperWindow->assertNoEvents();
1868}
1869
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001870/**
1871 * On the display, have a single window, and also an area where there's no window.
1872 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
1873 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
1874 */
1875TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
1876 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1877 sp<FakeWindowHandle> window =
1878 new FakeWindowHandle(application, mDispatcher, "Window", DISPLAY_ID);
1879
1880 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
1881 NotifyMotionArgs args;
1882
1883 // Touch down on the empty space
1884 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
1885
1886 mDispatcher->waitForIdle();
1887 window->assertNoEvents();
1888
1889 // Now touch down on the window with another pointer
1890 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
1891 mDispatcher->waitForIdle();
1892 window->consumeMotionDown();
1893}
1894
1895/**
1896 * Same test as above, but instead of touching the empty space, the first touch goes to
1897 * non-touchable window.
1898 */
1899TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
1900 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1901 sp<FakeWindowHandle> window1 =
1902 new FakeWindowHandle(application, mDispatcher, "Window1", DISPLAY_ID);
1903 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1904 window1->setTouchable(false);
1905 sp<FakeWindowHandle> window2 =
1906 new FakeWindowHandle(application, mDispatcher, "Window2", DISPLAY_ID);
1907 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1908
1909 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1910
1911 NotifyMotionArgs args;
1912 // Touch down on the non-touchable window
1913 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1914
1915 mDispatcher->waitForIdle();
1916 window1->assertNoEvents();
1917 window2->assertNoEvents();
1918
1919 // Now touch down on the window with another pointer
1920 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1921 mDispatcher->waitForIdle();
1922 window2->consumeMotionDown();
1923}
1924
Garfield Tandf26e862020-07-01 20:18:19 -07001925TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001926 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001927 sp<FakeWindowHandle> windowLeft =
1928 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1929 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001930 sp<FakeWindowHandle> windowRight =
1931 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1932 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001933
1934 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1935
1936 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1937
1938 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001939 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001940 injectMotionEvent(mDispatcher,
1941 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1942 AINPUT_SOURCE_MOUSE)
1943 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1944 .x(900)
1945 .y(400))
1946 .build()));
1947 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1948 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1949 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1950 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1951
1952 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001953 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001954 injectMotionEvent(mDispatcher,
1955 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1956 AINPUT_SOURCE_MOUSE)
1957 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1958 .x(300)
1959 .y(400))
1960 .build()));
1961 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1962 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1963 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1964 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1965 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1966 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1967
1968 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001970 injectMotionEvent(mDispatcher,
1971 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1972 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1973 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1974 .x(300)
1975 .y(400))
1976 .build()));
1977 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1978
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001979 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001980 injectMotionEvent(mDispatcher,
1981 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1982 AINPUT_SOURCE_MOUSE)
1983 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1984 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1985 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1986 .x(300)
1987 .y(400))
1988 .build()));
1989 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1990 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1991
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001992 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001993 injectMotionEvent(mDispatcher,
1994 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1995 AINPUT_SOURCE_MOUSE)
1996 .buttonState(0)
1997 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1998 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1999 .x(300)
2000 .y(400))
2001 .build()));
2002 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2003 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2004
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002005 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002006 injectMotionEvent(mDispatcher,
2007 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2008 .buttonState(0)
2009 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2010 .x(300)
2011 .y(400))
2012 .build()));
2013 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2014
2015 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002016 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002017 injectMotionEvent(mDispatcher,
2018 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2019 AINPUT_SOURCE_MOUSE)
2020 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2021 .x(900)
2022 .y(400))
2023 .build()));
2024 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2025 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2026 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2027 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2028 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2029 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2030}
2031
2032// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2033// directly in this test.
2034TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002035 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002036 sp<FakeWindowHandle> window =
2037 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2038 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002039
2040 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2041
2042 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2043
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002044 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002045 injectMotionEvent(mDispatcher,
2046 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2047 AINPUT_SOURCE_MOUSE)
2048 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2049 .x(300)
2050 .y(400))
2051 .build()));
2052 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2053 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2054
2055 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002056 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002057 injectMotionEvent(mDispatcher,
2058 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2059 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2060 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2061 .x(300)
2062 .y(400))
2063 .build()));
2064 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2065
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002066 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002067 injectMotionEvent(mDispatcher,
2068 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2069 AINPUT_SOURCE_MOUSE)
2070 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2071 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2072 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2073 .x(300)
2074 .y(400))
2075 .build()));
2076 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2077 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2078
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002079 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002080 injectMotionEvent(mDispatcher,
2081 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2082 AINPUT_SOURCE_MOUSE)
2083 .buttonState(0)
2084 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2085 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2086 .x(300)
2087 .y(400))
2088 .build()));
2089 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2090 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2091
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002092 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002093 injectMotionEvent(mDispatcher,
2094 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2095 .buttonState(0)
2096 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2097 .x(300)
2098 .y(400))
2099 .build()));
2100 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2101
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002102 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002103 injectMotionEvent(mDispatcher,
2104 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2105 AINPUT_SOURCE_MOUSE)
2106 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2107 .x(300)
2108 .y(400))
2109 .build()));
2110 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2111 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2112}
2113
Garfield Tan00f511d2019-06-12 16:55:40 -07002114TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002115 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002116
2117 sp<FakeWindowHandle> windowLeft =
2118 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2119 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002120 sp<FakeWindowHandle> windowRight =
2121 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2122 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002123
2124 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2125
Arthur Hung72d8dc32020-03-28 00:48:39 +00002126 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002127
2128 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2129 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002130 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002131 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002132 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002133 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002134 windowRight->assertNoEvents();
2135}
2136
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002137TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002138 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002139 sp<FakeWindowHandle> window =
2140 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002141 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002142
Arthur Hung72d8dc32020-03-28 00:48:39 +00002143 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002144 setFocusedWindow(window);
2145
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002146 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002147
2148 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2149 mDispatcher->notifyKey(&keyArgs);
2150
2151 // Window should receive key down event.
2152 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2153
2154 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2155 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002156 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002157 mDispatcher->notifyDeviceReset(&args);
2158 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2159 AKEY_EVENT_FLAG_CANCELED);
2160}
2161
2162TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002163 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002164 sp<FakeWindowHandle> window =
2165 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2166
Arthur Hung72d8dc32020-03-28 00:48:39 +00002167 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002168
2169 NotifyMotionArgs motionArgs =
2170 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2171 ADISPLAY_ID_DEFAULT);
2172 mDispatcher->notifyMotion(&motionArgs);
2173
2174 // Window should receive motion down event.
2175 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2176
2177 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2178 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002179 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002180 mDispatcher->notifyDeviceReset(&args);
2181 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2182 0 /*expectedFlags*/);
2183}
2184
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002185/**
2186 * Ensure the correct coordinate spaces are used by InputDispatcher.
2187 *
2188 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2189 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2190 * space.
2191 */
2192class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2193public:
2194 void SetUp() override {
2195 InputDispatcherTest::SetUp();
2196 mDisplayInfos.clear();
2197 mWindowInfos.clear();
2198 }
2199
2200 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2201 gui::DisplayInfo info;
2202 info.displayId = displayId;
2203 info.transform = transform;
2204 mDisplayInfos.push_back(std::move(info));
2205 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2206 }
2207
2208 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2209 mWindowInfos.push_back(*windowHandle->getInfo());
2210 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2211 }
2212
2213 // Set up a test scenario where the display has a scaled projection and there are two windows
2214 // on the display.
2215 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2216 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2217 // respectively.
2218 ui::Transform displayTransform;
2219 displayTransform.set(2, 0, 0, 4);
2220 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2221
2222 std::shared_ptr<FakeApplicationHandle> application =
2223 std::make_shared<FakeApplicationHandle>();
2224
2225 // Add two windows to the display. Their frames are represented in the display space.
2226 sp<FakeWindowHandle> firstWindow =
2227 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002228 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2229 addWindow(firstWindow);
2230
2231 sp<FakeWindowHandle> secondWindow =
2232 new FakeWindowHandle(application, mDispatcher, "Second Window",
2233 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002234 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2235 addWindow(secondWindow);
2236 return {std::move(firstWindow), std::move(secondWindow)};
2237 }
2238
2239private:
2240 std::vector<gui::DisplayInfo> mDisplayInfos;
2241 std::vector<gui::WindowInfo> mWindowInfos;
2242};
2243
2244TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2245 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2246 // Send down to the first window. The point is represented in the display space. The point is
2247 // selected so that if the hit test was done with the transform applied to it, then it would
2248 // end up in the incorrect window.
2249 NotifyMotionArgs downMotionArgs =
2250 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2251 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2252 mDispatcher->notifyMotion(&downMotionArgs);
2253
2254 firstWindow->consumeMotionDown();
2255 secondWindow->assertNoEvents();
2256}
2257
2258// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2259// the event should be treated as being in the logical display space.
2260TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2261 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2262 // Send down to the first window. The point is represented in the logical display space. The
2263 // point is selected so that if the hit test was done in logical display space, then it would
2264 // end up in the incorrect window.
2265 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2266 PointF{75 * 2, 55 * 4});
2267
2268 firstWindow->consumeMotionDown();
2269 secondWindow->assertNoEvents();
2270}
2271
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002272// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2273// event should be treated as being in the logical display space.
2274TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2275 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2276
2277 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2278 ui::Transform injectedEventTransform;
2279 injectedEventTransform.set(matrix);
2280 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2281 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2282
2283 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2284 .displayId(ADISPLAY_ID_DEFAULT)
2285 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2286 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2287 .x(untransformedPoint.x)
2288 .y(untransformedPoint.y))
2289 .build();
2290 event.transform(matrix);
2291
2292 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2293 InputEventInjectionSync::WAIT_FOR_RESULT);
2294
2295 firstWindow->consumeMotionDown();
2296 secondWindow->assertNoEvents();
2297}
2298
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002299TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2300 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2301
2302 // Send down to the second window.
2303 NotifyMotionArgs downMotionArgs =
2304 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2305 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2306 mDispatcher->notifyMotion(&downMotionArgs);
2307
2308 firstWindow->assertNoEvents();
2309 const MotionEvent* event = secondWindow->consumeMotion();
2310 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2311
2312 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2313 EXPECT_EQ(300, event->getRawX(0));
2314 EXPECT_EQ(880, event->getRawY(0));
2315
2316 // Ensure that the x and y values are in the window's coordinate space.
2317 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2318 // the logical display space. This will be the origin of the window space.
2319 EXPECT_EQ(100, event->getX(0));
2320 EXPECT_EQ(80, event->getY(0));
2321}
2322
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002323using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2324 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002325
2326class TransferTouchFixture : public InputDispatcherTest,
2327 public ::testing::WithParamInterface<TransferFunction> {};
2328
2329TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002330 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002331
2332 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002333 sp<FakeWindowHandle> firstWindow =
2334 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2335 sp<FakeWindowHandle> secondWindow =
2336 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002337
2338 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002339 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002340
2341 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002342 NotifyMotionArgs downMotionArgs =
2343 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2344 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002345 mDispatcher->notifyMotion(&downMotionArgs);
2346 // Only the first window should get the down event
2347 firstWindow->consumeMotionDown();
2348 secondWindow->assertNoEvents();
2349
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002350 // Transfer touch to the second window
2351 TransferFunction f = GetParam();
2352 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2353 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002354 // The first window gets cancel and the second gets down
2355 firstWindow->consumeMotionCancel();
2356 secondWindow->consumeMotionDown();
2357
2358 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002359 NotifyMotionArgs upMotionArgs =
2360 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2361 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002362 mDispatcher->notifyMotion(&upMotionArgs);
2363 // The first window gets no events and the second gets up
2364 firstWindow->assertNoEvents();
2365 secondWindow->consumeMotionUp();
2366}
2367
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002368TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002369 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002370
2371 PointF touchPoint = {10, 10};
2372
2373 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002374 sp<FakeWindowHandle> firstWindow =
2375 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002376 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002377 sp<FakeWindowHandle> secondWindow =
2378 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002379 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002380
2381 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002382 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002383
2384 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002385 NotifyMotionArgs downMotionArgs =
2386 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2387 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002388 mDispatcher->notifyMotion(&downMotionArgs);
2389 // Only the first window should get the down event
2390 firstWindow->consumeMotionDown();
2391 secondWindow->assertNoEvents();
2392
2393 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002394 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002395 generateMotionArgs(POINTER_1_DOWN, 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(&pointerDownMotionArgs);
2398 // Only the first window should get the pointer down event
2399 firstWindow->consumeMotionPointerDown(1);
2400 secondWindow->assertNoEvents();
2401
2402 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002403 TransferFunction f = GetParam();
2404 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2405 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002406 // The first window gets cancel and the second gets down and pointer down
2407 firstWindow->consumeMotionCancel();
2408 secondWindow->consumeMotionDown();
2409 secondWindow->consumeMotionPointerDown(1);
2410
2411 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002412 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002413 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002414 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002415 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2416 // The first window gets nothing and the second gets pointer up
2417 firstWindow->assertNoEvents();
2418 secondWindow->consumeMotionPointerUp(1);
2419
2420 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002421 NotifyMotionArgs upMotionArgs =
2422 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2423 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002424 mDispatcher->notifyMotion(&upMotionArgs);
2425 // The first window gets nothing and the second gets up
2426 firstWindow->assertNoEvents();
2427 secondWindow->consumeMotionUp();
2428}
2429
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002430// For the cases of single pointer touch and two pointers non-split touch, the api's
2431// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2432// for the case where there are multiple pointers split across several windows.
2433INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2434 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002435 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2436 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002437 return dispatcher->transferTouch(destChannelToken);
2438 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002439 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2440 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002441 return dispatcher->transferTouchFocus(from, to,
2442 false /*isDragAndDrop*/);
2443 }));
2444
Svet Ganov5d3bc372020-01-26 23:11:07 -08002445TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002446 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002447
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002448 sp<FakeWindowHandle> firstWindow =
2449 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002450 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002451
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002452 sp<FakeWindowHandle> secondWindow =
2453 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002454 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002455
2456 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002457 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002458
2459 PointF pointInFirst = {300, 200};
2460 PointF pointInSecond = {300, 600};
2461
2462 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002463 NotifyMotionArgs firstDownMotionArgs =
2464 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2465 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002466 mDispatcher->notifyMotion(&firstDownMotionArgs);
2467 // Only the first window should get the down event
2468 firstWindow->consumeMotionDown();
2469 secondWindow->assertNoEvents();
2470
2471 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002472 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002473 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002474 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002475 mDispatcher->notifyMotion(&secondDownMotionArgs);
2476 // The first window gets a move and the second a down
2477 firstWindow->consumeMotionMove();
2478 secondWindow->consumeMotionDown();
2479
2480 // Transfer touch focus to the second window
2481 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2482 // The first window gets cancel and the new gets pointer down (it already saw down)
2483 firstWindow->consumeMotionCancel();
2484 secondWindow->consumeMotionPointerDown(1);
2485
2486 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002487 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002488 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002489 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002490 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2491 // The first window gets nothing and the second gets pointer up
2492 firstWindow->assertNoEvents();
2493 secondWindow->consumeMotionPointerUp(1);
2494
2495 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002496 NotifyMotionArgs upMotionArgs =
2497 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2498 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002499 mDispatcher->notifyMotion(&upMotionArgs);
2500 // The first window gets nothing and the second gets up
2501 firstWindow->assertNoEvents();
2502 secondWindow->consumeMotionUp();
2503}
2504
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002505// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2506// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2507// touch is not supported, so the touch should continue on those windows and the transferred-to
2508// window should get nothing.
2509TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2510 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2511
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002512 sp<FakeWindowHandle> firstWindow =
2513 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2514 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002515
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002516 sp<FakeWindowHandle> secondWindow =
2517 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2518 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002519
2520 // Add the windows to the dispatcher
2521 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2522
2523 PointF pointInFirst = {300, 200};
2524 PointF pointInSecond = {300, 600};
2525
2526 // Send down to the first window
2527 NotifyMotionArgs firstDownMotionArgs =
2528 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2529 ADISPLAY_ID_DEFAULT, {pointInFirst});
2530 mDispatcher->notifyMotion(&firstDownMotionArgs);
2531 // Only the first window should get the down event
2532 firstWindow->consumeMotionDown();
2533 secondWindow->assertNoEvents();
2534
2535 // Send down to the second window
2536 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002537 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002538 {pointInFirst, pointInSecond});
2539 mDispatcher->notifyMotion(&secondDownMotionArgs);
2540 // The first window gets a move and the second a down
2541 firstWindow->consumeMotionMove();
2542 secondWindow->consumeMotionDown();
2543
2544 // Transfer touch focus to the second window
2545 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2546 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2547 ASSERT_FALSE(transferred);
2548 firstWindow->assertNoEvents();
2549 secondWindow->assertNoEvents();
2550
2551 // The rest of the dispatch should proceed as normal
2552 // Send pointer up to the second window
2553 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002554 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002555 {pointInFirst, pointInSecond});
2556 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2557 // The first window gets MOVE and the second gets pointer up
2558 firstWindow->consumeMotionMove();
2559 secondWindow->consumeMotionUp();
2560
2561 // Send up event to the first window
2562 NotifyMotionArgs upMotionArgs =
2563 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2564 ADISPLAY_ID_DEFAULT);
2565 mDispatcher->notifyMotion(&upMotionArgs);
2566 // The first window gets nothing and the second gets up
2567 firstWindow->consumeMotionUp();
2568 secondWindow->assertNoEvents();
2569}
2570
Arthur Hungabbb9d82021-09-01 14:52:30 +00002571// This case will create two windows and one mirrored window on the default display and mirror
2572// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2573// the windows info of second display before default display.
2574TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2575 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2576 sp<FakeWindowHandle> firstWindowInPrimary =
2577 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2578 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002579 sp<FakeWindowHandle> secondWindowInPrimary =
2580 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2581 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002582
2583 sp<FakeWindowHandle> mirrorWindowInPrimary =
2584 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2585 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002586
2587 sp<FakeWindowHandle> firstWindowInSecondary =
2588 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2589 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002590
2591 sp<FakeWindowHandle> secondWindowInSecondary =
2592 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2593 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002594
2595 // Update window info, let it find window handle of second display first.
2596 mDispatcher->setInputWindows(
2597 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2598 {ADISPLAY_ID_DEFAULT,
2599 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2600
2601 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2602 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2603 {50, 50}))
2604 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2605
2606 // Window should receive motion event.
2607 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2608
2609 // Transfer touch focus
2610 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2611 secondWindowInPrimary->getToken()));
2612 // The first window gets cancel.
2613 firstWindowInPrimary->consumeMotionCancel();
2614 secondWindowInPrimary->consumeMotionDown();
2615
2616 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2617 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2618 ADISPLAY_ID_DEFAULT, {150, 50}))
2619 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2620 firstWindowInPrimary->assertNoEvents();
2621 secondWindowInPrimary->consumeMotionMove();
2622
2623 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2624 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2625 {150, 50}))
2626 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2627 firstWindowInPrimary->assertNoEvents();
2628 secondWindowInPrimary->consumeMotionUp();
2629}
2630
2631// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2632// 'transferTouch' api.
2633TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2634 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2635 sp<FakeWindowHandle> firstWindowInPrimary =
2636 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2637 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002638 sp<FakeWindowHandle> secondWindowInPrimary =
2639 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2640 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002641
2642 sp<FakeWindowHandle> mirrorWindowInPrimary =
2643 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2644 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002645
2646 sp<FakeWindowHandle> firstWindowInSecondary =
2647 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2648 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002649
2650 sp<FakeWindowHandle> secondWindowInSecondary =
2651 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2652 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002653
2654 // Update window info, let it find window handle of second display first.
2655 mDispatcher->setInputWindows(
2656 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2657 {ADISPLAY_ID_DEFAULT,
2658 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2659
2660 // Touch on second display.
2661 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2662 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2663 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2664
2665 // Window should receive motion event.
2666 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2667
2668 // Transfer touch focus
2669 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2670
2671 // The first window gets cancel.
2672 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2673 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2674
2675 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2676 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2677 SECOND_DISPLAY_ID, {150, 50}))
2678 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2679 firstWindowInPrimary->assertNoEvents();
2680 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2681
2682 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2683 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2684 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2685 firstWindowInPrimary->assertNoEvents();
2686 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2687}
2688
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002689TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
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
Vishnu Nair47074b82020-08-14 11:54:47 -07002694 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002695 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002696 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002697
2698 window->consumeFocusEvent(true);
2699
2700 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2701 mDispatcher->notifyKey(&keyArgs);
2702
2703 // Window should receive key down event.
2704 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2705}
2706
2707TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002708 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002709 sp<FakeWindowHandle> window =
2710 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2711
Arthur Hung72d8dc32020-03-28 00:48:39 +00002712 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002713
2714 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2715 mDispatcher->notifyKey(&keyArgs);
2716 mDispatcher->waitForIdle();
2717
2718 window->assertNoEvents();
2719}
2720
2721// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2722TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002723 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002724 sp<FakeWindowHandle> window =
2725 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2726
Arthur Hung72d8dc32020-03-28 00:48:39 +00002727 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002728
2729 // Send key
2730 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2731 mDispatcher->notifyKey(&keyArgs);
2732 // Send motion
2733 NotifyMotionArgs motionArgs =
2734 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2735 ADISPLAY_ID_DEFAULT);
2736 mDispatcher->notifyMotion(&motionArgs);
2737
2738 // Window should receive only the motion event
2739 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2740 window->assertNoEvents(); // Key event or focus event will not be received
2741}
2742
arthurhungea3f4fc2020-12-21 23:18:53 +08002743TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2744 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2745
arthurhungea3f4fc2020-12-21 23:18:53 +08002746 sp<FakeWindowHandle> firstWindow =
2747 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2748 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08002749
arthurhungea3f4fc2020-12-21 23:18:53 +08002750 sp<FakeWindowHandle> secondWindow =
2751 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2752 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08002753
2754 // Add the windows to the dispatcher
2755 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2756
2757 PointF pointInFirst = {300, 200};
2758 PointF pointInSecond = {300, 600};
2759
2760 // Send down to the first window
2761 NotifyMotionArgs firstDownMotionArgs =
2762 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2763 ADISPLAY_ID_DEFAULT, {pointInFirst});
2764 mDispatcher->notifyMotion(&firstDownMotionArgs);
2765 // Only the first window should get the down event
2766 firstWindow->consumeMotionDown();
2767 secondWindow->assertNoEvents();
2768
2769 // Send down to the second window
2770 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002771 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08002772 {pointInFirst, pointInSecond});
2773 mDispatcher->notifyMotion(&secondDownMotionArgs);
2774 // The first window gets a move and the second a down
2775 firstWindow->consumeMotionMove();
2776 secondWindow->consumeMotionDown();
2777
2778 // Send pointer cancel to the second window
2779 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002780 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08002781 {pointInFirst, pointInSecond});
2782 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2783 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2784 // The first window gets move and the second gets cancel.
2785 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2786 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2787
2788 // Send up event.
2789 NotifyMotionArgs upMotionArgs =
2790 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2791 ADISPLAY_ID_DEFAULT);
2792 mDispatcher->notifyMotion(&upMotionArgs);
2793 // The first window gets up and the second gets nothing.
2794 firstWindow->consumeMotionUp();
2795 secondWindow->assertNoEvents();
2796}
2797
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002798TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2799 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2800
2801 sp<FakeWindowHandle> window =
2802 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2803 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2804 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2805 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2806 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2807
2808 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2809 window->assertNoEvents();
2810 mDispatcher->waitForIdle();
2811}
2812
chaviwd1c23182019-12-20 18:44:56 -08002813class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002814public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002815 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002816 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07002817 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002818 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002819 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002820 }
2821
chaviwd1c23182019-12-20 18:44:56 -08002822 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2823
2824 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2825 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2826 expectedDisplayId, expectedFlags);
2827 }
2828
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002829 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2830
2831 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2832
chaviwd1c23182019-12-20 18:44:56 -08002833 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2834 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2835 expectedDisplayId, expectedFlags);
2836 }
2837
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002838 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2839 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2840 expectedDisplayId, expectedFlags);
2841 }
2842
chaviwd1c23182019-12-20 18:44:56 -08002843 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2844 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2845 expectedDisplayId, expectedFlags);
2846 }
2847
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002848 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2849 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2850 expectedDisplayId, expectedFlags);
2851 }
2852
Arthur Hungfbfa5722021-11-16 02:45:54 +00002853 void consumeMotionPointerDown(int32_t pointerIdx) {
2854 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2855 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2856 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2857 0 /*expectedFlags*/);
2858 }
2859
Evan Rosky84f07f02021-04-16 10:42:42 -07002860 MotionEvent* consumeMotion() {
2861 InputEvent* event = mInputReceiver->consume();
2862 if (!event) {
2863 ADD_FAILURE() << "No event was produced";
2864 return nullptr;
2865 }
2866 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2867 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2868 return nullptr;
2869 }
2870 return static_cast<MotionEvent*>(event);
2871 }
2872
chaviwd1c23182019-12-20 18:44:56 -08002873 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2874
2875private:
2876 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002877};
2878
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002879using InputDispatcherMonitorTest = InputDispatcherTest;
2880
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002881/**
2882 * Two entities that receive touch: A window, and a global monitor.
2883 * The touch goes to the window, and then the window disappears.
2884 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2885 * for the monitor, as well.
2886 * 1. foregroundWindow
2887 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2888 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002889TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002890 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2891 sp<FakeWindowHandle> window =
2892 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2893
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002894 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002895
2896 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2897 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2898 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2899 {100, 200}))
2900 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2901
2902 // Both the foreground window and the global monitor should receive the touch down
2903 window->consumeMotionDown();
2904 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2905
2906 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2907 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2908 ADISPLAY_ID_DEFAULT, {110, 200}))
2909 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2910
2911 window->consumeMotionMove();
2912 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2913
2914 // Now the foreground window goes away
2915 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2916 window->consumeMotionCancel();
2917 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2918
2919 // If more events come in, there will be no more foreground window to send them to. This will
2920 // cause a cancel for the monitor, as well.
2921 ASSERT_EQ(InputEventInjectionResult::FAILED,
2922 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2923 ADISPLAY_ID_DEFAULT, {120, 200}))
2924 << "Injection should fail because the window was removed";
2925 window->assertNoEvents();
2926 // Global monitor now gets the cancel
2927 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2928}
2929
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002930TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002931 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002932 sp<FakeWindowHandle> window =
2933 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002934 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002935
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002936 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002937
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002938 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002939 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002940 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002941 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002942 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002943}
2944
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002945TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
2946 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002947
Chris Yea209fde2020-07-22 13:54:51 -07002948 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002949 sp<FakeWindowHandle> window =
2950 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002951 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002952
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002953 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002954 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002955 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002956 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002957 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002958
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002959 // Pilfer pointers from the monitor.
2960 // This should not do anything and the window should continue to receive events.
2961 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00002962
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002963 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002964 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2965 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002966 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002967
2968 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2969 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002970}
2971
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002972TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07002973 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2974 sp<FakeWindowHandle> window =
2975 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2976 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2977 window->setWindowOffset(20, 40);
2978 window->setWindowTransform(0, 1, -1, 0);
2979
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002980 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07002981
2982 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2983 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2984 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2985 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2986 MotionEvent* event = monitor.consumeMotion();
2987 // Even though window has transform, gesture monitor must not.
2988 ASSERT_EQ(ui::Transform(), event->getTransform());
2989}
2990
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002991TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002992 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002993 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00002994
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002995 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00002996 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002997 << "Injection should fail if there is a monitor, but no touchable window";
2998 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00002999}
3000
chaviw81e2bb92019-12-18 15:03:51 -08003001TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003002 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08003003 sp<FakeWindowHandle> window =
3004 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3005
Arthur Hung72d8dc32020-03-28 00:48:39 +00003006 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003007
3008 NotifyMotionArgs motionArgs =
3009 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3010 ADISPLAY_ID_DEFAULT);
3011
3012 mDispatcher->notifyMotion(&motionArgs);
3013 // Window should receive motion down event.
3014 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3015
3016 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003017 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003018 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3019 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3020 motionArgs.pointerCoords[0].getX() - 10);
3021
3022 mDispatcher->notifyMotion(&motionArgs);
3023 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3024 0 /*expectedFlags*/);
3025}
3026
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003027/**
3028 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3029 * the device default right away. In the test scenario, we check both the default value,
3030 * and the action of enabling / disabling.
3031 */
3032TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003033 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003034 sp<FakeWindowHandle> window =
3035 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003036 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003037
3038 // Set focused application.
3039 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003040 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003041
3042 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003043 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003044 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003045 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3046
3047 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003048 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003049 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003050 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3051
3052 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003053 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3054 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003055 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003056 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003057 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003058 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003059 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3060
3061 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003062 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003063 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003064 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3065
3066 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003067 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3068 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003069 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003070 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003071 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003072 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003073 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3074
3075 window->assertNoEvents();
3076}
3077
Gang Wange9087892020-01-07 12:17:14 -05003078TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003079 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003080 sp<FakeWindowHandle> window =
3081 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3082
3083 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003084 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003085
Arthur Hung72d8dc32020-03-28 00:48:39 +00003086 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003087 setFocusedWindow(window);
3088
Gang Wange9087892020-01-07 12:17:14 -05003089 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3090
3091 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3092 mDispatcher->notifyKey(&keyArgs);
3093
3094 InputEvent* event = window->consume();
3095 ASSERT_NE(event, nullptr);
3096
3097 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3098 ASSERT_NE(verified, nullptr);
3099 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3100
3101 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3102 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3103 ASSERT_EQ(keyArgs.source, verified->source);
3104 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3105
3106 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3107
3108 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003109 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003110 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003111 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3112 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3113 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3114 ASSERT_EQ(0, verifiedKey.repeatCount);
3115}
3116
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003117TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003118 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003119 sp<FakeWindowHandle> window =
3120 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3121
3122 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3123
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003124 ui::Transform transform;
3125 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3126
3127 gui::DisplayInfo displayInfo;
3128 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3129 displayInfo.transform = transform;
3130
3131 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003132
3133 NotifyMotionArgs motionArgs =
3134 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3135 ADISPLAY_ID_DEFAULT);
3136 mDispatcher->notifyMotion(&motionArgs);
3137
3138 InputEvent* event = window->consume();
3139 ASSERT_NE(event, nullptr);
3140
3141 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3142 ASSERT_NE(verified, nullptr);
3143 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3144
3145 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3146 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3147 EXPECT_EQ(motionArgs.source, verified->source);
3148 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3149
3150 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3151
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003152 const vec2 rawXY =
3153 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3154 motionArgs.pointerCoords[0].getXYValue());
3155 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3156 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003157 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003158 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003159 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003160 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3161 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3162}
3163
chaviw09c8d2d2020-08-24 15:48:26 -07003164/**
3165 * Ensure that separate calls to sign the same data are generating the same key.
3166 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3167 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3168 * tests.
3169 */
3170TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3171 KeyEvent event = getTestKeyEvent();
3172 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3173
3174 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3175 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3176 ASSERT_EQ(hmac1, hmac2);
3177}
3178
3179/**
3180 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3181 */
3182TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3183 KeyEvent event = getTestKeyEvent();
3184 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3185 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3186
3187 verifiedEvent.deviceId += 1;
3188 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3189
3190 verifiedEvent.source += 1;
3191 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3192
3193 verifiedEvent.eventTimeNanos += 1;
3194 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3195
3196 verifiedEvent.displayId += 1;
3197 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3198
3199 verifiedEvent.action += 1;
3200 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3201
3202 verifiedEvent.downTimeNanos += 1;
3203 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3204
3205 verifiedEvent.flags += 1;
3206 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3207
3208 verifiedEvent.keyCode += 1;
3209 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3210
3211 verifiedEvent.scanCode += 1;
3212 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3213
3214 verifiedEvent.metaState += 1;
3215 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3216
3217 verifiedEvent.repeatCount += 1;
3218 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3219}
3220
Vishnu Nair958da932020-08-21 17:12:37 -07003221TEST_F(InputDispatcherTest, SetFocusedWindow) {
3222 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3223 sp<FakeWindowHandle> windowTop =
3224 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3225 sp<FakeWindowHandle> windowSecond =
3226 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3227 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3228
3229 // Top window is also focusable but is not granted focus.
3230 windowTop->setFocusable(true);
3231 windowSecond->setFocusable(true);
3232 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3233 setFocusedWindow(windowSecond);
3234
3235 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003236 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3237 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003238
3239 // Focused window should receive event.
3240 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3241 windowTop->assertNoEvents();
3242}
3243
3244TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3245 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3246 sp<FakeWindowHandle> window =
3247 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3248 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3249
3250 window->setFocusable(true);
3251 // Release channel for window is no longer valid.
3252 window->releaseChannel();
3253 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
3260 // window channel is invalid, so it should not receive any input event.
3261 window->assertNoEvents();
3262}
3263
3264TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3265 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3266 sp<FakeWindowHandle> window =
3267 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003268 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003269 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3270
Vishnu Nair958da932020-08-21 17:12:37 -07003271 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3272 setFocusedWindow(window);
3273
3274 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003275 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3276 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003277
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003278 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003279 window->assertNoEvents();
3280}
3281
3282TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3283 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3284 sp<FakeWindowHandle> windowTop =
3285 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3286 sp<FakeWindowHandle> windowSecond =
3287 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3288 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3289
3290 windowTop->setFocusable(true);
3291 windowSecond->setFocusable(true);
3292 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3293 setFocusedWindow(windowTop);
3294 windowTop->consumeFocusEvent(true);
3295
3296 setFocusedWindow(windowSecond, windowTop);
3297 windowSecond->consumeFocusEvent(true);
3298 windowTop->consumeFocusEvent(false);
3299
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003300 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3301 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003302
3303 // Focused window should receive event.
3304 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3305}
3306
3307TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3308 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3309 sp<FakeWindowHandle> windowTop =
3310 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3311 sp<FakeWindowHandle> windowSecond =
3312 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3313 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3314
3315 windowTop->setFocusable(true);
3316 windowSecond->setFocusable(true);
3317 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3318 setFocusedWindow(windowSecond, windowTop);
3319
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003320 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3321 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003322
3323 // Event should be dropped.
3324 windowTop->assertNoEvents();
3325 windowSecond->assertNoEvents();
3326}
3327
3328TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3329 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3330 sp<FakeWindowHandle> window =
3331 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3332 sp<FakeWindowHandle> previousFocusedWindow =
3333 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3334 ADISPLAY_ID_DEFAULT);
3335 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3336
3337 window->setFocusable(true);
3338 previousFocusedWindow->setFocusable(true);
3339 window->setVisible(false);
3340 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3341 setFocusedWindow(previousFocusedWindow);
3342 previousFocusedWindow->consumeFocusEvent(true);
3343
3344 // Requesting focus on invisible window takes focus from currently focused window.
3345 setFocusedWindow(window);
3346 previousFocusedWindow->consumeFocusEvent(false);
3347
3348 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003349 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003350 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003351 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003352
3353 // Window does not get focus event or key down.
3354 window->assertNoEvents();
3355
3356 // Window becomes visible.
3357 window->setVisible(true);
3358 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3359
3360 // Window receives focus event.
3361 window->consumeFocusEvent(true);
3362 // Focused window receives key down.
3363 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3364}
3365
Vishnu Nair599f1412021-06-21 10:39:58 -07003366TEST_F(InputDispatcherTest, DisplayRemoved) {
3367 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3368 sp<FakeWindowHandle> window =
3369 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3370 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3371
3372 // window is granted focus.
3373 window->setFocusable(true);
3374 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3375 setFocusedWindow(window);
3376 window->consumeFocusEvent(true);
3377
3378 // When a display is removed window loses focus.
3379 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3380 window->consumeFocusEvent(false);
3381}
3382
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003383/**
3384 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3385 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3386 * of the 'slipperyEnterWindow'.
3387 *
3388 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3389 * a way so that the touched location is no longer covered by the top window.
3390 *
3391 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3392 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3393 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3394 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3395 * with ACTION_DOWN).
3396 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3397 * window moved itself away from the touched location and had Flag::SLIPPERY.
3398 *
3399 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3400 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3401 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3402 *
3403 * In this test, we ensure that the event received by the bottom window has
3404 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3405 */
3406TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3407 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3408 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3409
3410 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3411 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3412
3413 sp<FakeWindowHandle> slipperyExitWindow =
3414 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003415 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003416 // Make sure this one overlaps the bottom window
3417 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3418 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3419 // one. Windows with the same owner are not considered to be occluding each other.
3420 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3421
3422 sp<FakeWindowHandle> slipperyEnterWindow =
3423 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3424 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3425
3426 mDispatcher->setInputWindows(
3427 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3428
3429 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3430 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3431 ADISPLAY_ID_DEFAULT, {{50, 50}});
3432 mDispatcher->notifyMotion(&args);
3433 slipperyExitWindow->consumeMotionDown();
3434 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3435 mDispatcher->setInputWindows(
3436 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3437
3438 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3439 ADISPLAY_ID_DEFAULT, {{51, 51}});
3440 mDispatcher->notifyMotion(&args);
3441
3442 slipperyExitWindow->consumeMotionCancel();
3443
3444 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3445 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3446}
3447
Garfield Tan1c7bc862020-01-28 13:24:04 -08003448class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3449protected:
3450 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3451 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3452
Chris Yea209fde2020-07-22 13:54:51 -07003453 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003454 sp<FakeWindowHandle> mWindow;
3455
3456 virtual void SetUp() override {
3457 mFakePolicy = new FakeInputDispatcherPolicy();
3458 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003459 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003460 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3461 ASSERT_EQ(OK, mDispatcher->start());
3462
3463 setUpWindow();
3464 }
3465
3466 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003467 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003468 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3469
Vishnu Nair47074b82020-08-14 11:54:47 -07003470 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003471 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003472 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003473 mWindow->consumeFocusEvent(true);
3474 }
3475
Chris Ye2ad95392020-09-01 13:44:44 -07003476 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003477 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003478 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003479 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3480 mDispatcher->notifyKey(&keyArgs);
3481
3482 // Window should receive key down event.
3483 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3484 }
3485
3486 void expectKeyRepeatOnce(int32_t repeatCount) {
3487 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3488 InputEvent* repeatEvent = mWindow->consume();
3489 ASSERT_NE(nullptr, repeatEvent);
3490
3491 uint32_t eventType = repeatEvent->getType();
3492 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3493
3494 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3495 uint32_t eventAction = repeatKeyEvent->getAction();
3496 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3497 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3498 }
3499
Chris Ye2ad95392020-09-01 13:44:44 -07003500 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003501 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003502 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003503 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3504 mDispatcher->notifyKey(&keyArgs);
3505
3506 // Window should receive key down event.
3507 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3508 0 /*expectedFlags*/);
3509 }
3510};
3511
3512TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003513 sendAndConsumeKeyDown(1 /* deviceId */);
3514 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3515 expectKeyRepeatOnce(repeatCount);
3516 }
3517}
3518
3519TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3520 sendAndConsumeKeyDown(1 /* deviceId */);
3521 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3522 expectKeyRepeatOnce(repeatCount);
3523 }
3524 sendAndConsumeKeyDown(2 /* deviceId */);
3525 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003526 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3527 expectKeyRepeatOnce(repeatCount);
3528 }
3529}
3530
3531TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003532 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003533 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003534 sendAndConsumeKeyUp(1 /* deviceId */);
3535 mWindow->assertNoEvents();
3536}
3537
3538TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3539 sendAndConsumeKeyDown(1 /* deviceId */);
3540 expectKeyRepeatOnce(1 /*repeatCount*/);
3541 sendAndConsumeKeyDown(2 /* deviceId */);
3542 expectKeyRepeatOnce(1 /*repeatCount*/);
3543 // Stale key up from device 1.
3544 sendAndConsumeKeyUp(1 /* deviceId */);
3545 // Device 2 is still down, keep repeating
3546 expectKeyRepeatOnce(2 /*repeatCount*/);
3547 expectKeyRepeatOnce(3 /*repeatCount*/);
3548 // Device 2 key up
3549 sendAndConsumeKeyUp(2 /* deviceId */);
3550 mWindow->assertNoEvents();
3551}
3552
3553TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3554 sendAndConsumeKeyDown(1 /* deviceId */);
3555 expectKeyRepeatOnce(1 /*repeatCount*/);
3556 sendAndConsumeKeyDown(2 /* deviceId */);
3557 expectKeyRepeatOnce(1 /*repeatCount*/);
3558 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3559 sendAndConsumeKeyUp(2 /* deviceId */);
3560 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003561 mWindow->assertNoEvents();
3562}
3563
liushenxiang42232912021-05-21 20:24:09 +08003564TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3565 sendAndConsumeKeyDown(DEVICE_ID);
3566 expectKeyRepeatOnce(1 /*repeatCount*/);
3567 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3568 mDispatcher->notifyDeviceReset(&args);
3569 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3570 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3571 mWindow->assertNoEvents();
3572}
3573
Garfield Tan1c7bc862020-01-28 13:24:04 -08003574TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003575 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003576 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3577 InputEvent* repeatEvent = mWindow->consume();
3578 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3579 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3580 IdGenerator::getSource(repeatEvent->getId()));
3581 }
3582}
3583
3584TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003585 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003586
3587 std::unordered_set<int32_t> idSet;
3588 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3589 InputEvent* repeatEvent = mWindow->consume();
3590 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3591 int32_t id = repeatEvent->getId();
3592 EXPECT_EQ(idSet.end(), idSet.find(id));
3593 idSet.insert(id);
3594 }
3595}
3596
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003597/* Test InputDispatcher for MultiDisplay */
3598class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3599public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003600 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003601 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003602
Chris Yea209fde2020-07-22 13:54:51 -07003603 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003604 windowInPrimary =
3605 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003606
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003607 // Set focus window for primary display, but focused display would be second one.
3608 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003609 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003610 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003611 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003612 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003613
Chris Yea209fde2020-07-22 13:54:51 -07003614 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003615 windowInSecondary =
3616 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003617 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003618 // Set focus display to second one.
3619 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3620 // Set focus window for second display.
3621 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003622 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003623 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003624 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003625 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003626 }
3627
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003628 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003629 InputDispatcherTest::TearDown();
3630
Chris Yea209fde2020-07-22 13:54:51 -07003631 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003632 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003633 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003634 windowInSecondary.clear();
3635 }
3636
3637protected:
Chris Yea209fde2020-07-22 13:54:51 -07003638 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003639 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003640 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003641 sp<FakeWindowHandle> windowInSecondary;
3642};
3643
3644TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3645 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003646 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3647 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3648 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003649 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003650 windowInSecondary->assertNoEvents();
3651
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003652 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003653 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3654 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3655 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003656 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003657 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003658}
3659
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003660TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003661 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003662 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3663 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003664 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003665 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003666 windowInSecondary->assertNoEvents();
3667
3668 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003669 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003670 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003671 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003672 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003673
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003674 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003675 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003676
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003677 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003678 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3679 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003680
3681 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003682 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003683 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003684 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003685 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003686 windowInSecondary->assertNoEvents();
3687}
3688
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003689// Test per-display input monitors for motion event.
3690TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003691 FakeMonitorReceiver monitorInPrimary =
3692 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3693 FakeMonitorReceiver monitorInSecondary =
3694 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003695
3696 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003697 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3698 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3699 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003700 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003701 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003702 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003703 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003704
3705 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003706 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3707 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3708 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003709 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003710 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003711 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003712 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003713
3714 // Test inject a non-pointer motion event.
3715 // If specific a display, it will dispatch to the focused window of particular display,
3716 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003717 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3718 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3719 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003720 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003721 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003722 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003723 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003724}
3725
3726// Test per-display input monitors for key event.
3727TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003728 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003729 FakeMonitorReceiver monitorInPrimary =
3730 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3731 FakeMonitorReceiver monitorInSecondary =
3732 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003733
3734 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003735 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3736 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003737 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003738 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003739 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003740 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003741}
3742
Vishnu Nair958da932020-08-21 17:12:37 -07003743TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3744 sp<FakeWindowHandle> secondWindowInPrimary =
3745 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3746 secondWindowInPrimary->setFocusable(true);
3747 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3748 setFocusedWindow(secondWindowInPrimary);
3749 windowInPrimary->consumeFocusEvent(false);
3750 secondWindowInPrimary->consumeFocusEvent(true);
3751
3752 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003753 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3754 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003755 windowInPrimary->assertNoEvents();
3756 windowInSecondary->assertNoEvents();
3757 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3758}
3759
Arthur Hungdfd528e2021-12-08 13:23:04 +00003760TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3761 FakeMonitorReceiver monitorInPrimary =
3762 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3763 FakeMonitorReceiver monitorInSecondary =
3764 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3765
3766 // Test touch down on primary display.
3767 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3768 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3769 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3770 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3771 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3772
3773 // Test touch down on second display.
3774 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3775 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3776 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3777 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3778 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3779
3780 // Trigger cancel touch.
3781 mDispatcher->cancelCurrentTouch();
3782 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3783 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3784 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3785 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3786
3787 // Test inject a move motion event, no window/monitor should receive the event.
3788 ASSERT_EQ(InputEventInjectionResult::FAILED,
3789 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3790 ADISPLAY_ID_DEFAULT, {110, 200}))
3791 << "Inject motion event should return InputEventInjectionResult::FAILED";
3792 windowInPrimary->assertNoEvents();
3793 monitorInPrimary.assertNoEvents();
3794
3795 ASSERT_EQ(InputEventInjectionResult::FAILED,
3796 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3797 SECOND_DISPLAY_ID, {110, 200}))
3798 << "Inject motion event should return InputEventInjectionResult::FAILED";
3799 windowInSecondary->assertNoEvents();
3800 monitorInSecondary.assertNoEvents();
3801}
3802
Jackal Guof9696682018-10-05 12:23:23 +08003803class InputFilterTest : public InputDispatcherTest {
3804protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003805 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3806 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003807 NotifyMotionArgs motionArgs;
3808
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003809 motionArgs =
3810 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003811 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003812 motionArgs =
3813 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003814 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003815 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003816 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003817 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3818 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003819 } else {
3820 mFakePolicy->assertFilterInputEventWasNotCalled();
3821 }
3822 }
3823
3824 void testNotifyKey(bool expectToBeFiltered) {
3825 NotifyKeyArgs keyArgs;
3826
3827 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3828 mDispatcher->notifyKey(&keyArgs);
3829 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3830 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003831 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003832
3833 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003834 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003835 } else {
3836 mFakePolicy->assertFilterInputEventWasNotCalled();
3837 }
3838 }
3839};
3840
3841// Test InputFilter for MotionEvent
3842TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3843 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3844 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3845 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3846
3847 // Enable InputFilter
3848 mDispatcher->setInputFilterEnabled(true);
3849 // Test touch on both primary and second display, and check if both events are filtered.
3850 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3851 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3852
3853 // Disable InputFilter
3854 mDispatcher->setInputFilterEnabled(false);
3855 // Test touch on both primary and second display, and check if both events aren't filtered.
3856 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3857 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3858}
3859
3860// Test InputFilter for KeyEvent
3861TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3862 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3863 testNotifyKey(/*expectToBeFiltered*/ false);
3864
3865 // Enable InputFilter
3866 mDispatcher->setInputFilterEnabled(true);
3867 // Send a key event, and check if it is filtered.
3868 testNotifyKey(/*expectToBeFiltered*/ true);
3869
3870 // Disable InputFilter
3871 mDispatcher->setInputFilterEnabled(false);
3872 // Send a key event, and check if it isn't filtered.
3873 testNotifyKey(/*expectToBeFiltered*/ false);
3874}
3875
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003876// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3877// logical display coordinate space.
3878TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3879 ui::Transform firstDisplayTransform;
3880 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3881 ui::Transform secondDisplayTransform;
3882 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3883
3884 std::vector<gui::DisplayInfo> displayInfos(2);
3885 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3886 displayInfos[0].transform = firstDisplayTransform;
3887 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3888 displayInfos[1].transform = secondDisplayTransform;
3889
3890 mDispatcher->onWindowInfosChanged({}, displayInfos);
3891
3892 // Enable InputFilter
3893 mDispatcher->setInputFilterEnabled(true);
3894
3895 // Ensure the correct transforms are used for the displays.
3896 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3897 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3898}
3899
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003900class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3901protected:
3902 virtual void SetUp() override {
3903 InputDispatcherTest::SetUp();
3904
3905 /**
3906 * We don't need to enable input filter to test the injected event policy, but we enabled it
3907 * here to make the tests more realistic, since this policy only matters when inputfilter is
3908 * on.
3909 */
3910 mDispatcher->setInputFilterEnabled(true);
3911
3912 std::shared_ptr<InputApplicationHandle> application =
3913 std::make_shared<FakeApplicationHandle>();
3914 mWindow =
3915 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3916
3917 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3918 mWindow->setFocusable(true);
3919 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3920 setFocusedWindow(mWindow);
3921 mWindow->consumeFocusEvent(true);
3922 }
3923
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003924 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3925 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003926 KeyEvent event;
3927
3928 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3929 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3930 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3931 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3932 const int32_t additionalPolicyFlags =
3933 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3934 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3935 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3936 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3937 policyFlags | additionalPolicyFlags));
3938
3939 InputEvent* received = mWindow->consume();
3940 ASSERT_NE(nullptr, received);
3941 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003942 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3943 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3944 ASSERT_EQ(flags, keyEvent.getFlags());
3945 }
3946
3947 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3948 int32_t flags) {
3949 MotionEvent event;
3950 PointerProperties pointerProperties[1];
3951 PointerCoords pointerCoords[1];
3952 pointerProperties[0].clear();
3953 pointerProperties[0].id = 0;
3954 pointerCoords[0].clear();
3955 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3956 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3957
3958 ui::Transform identityTransform;
3959 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3960 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3961 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3962 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3963 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003964 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003965 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003966 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3967
3968 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3970 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3971 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3972 policyFlags | additionalPolicyFlags));
3973
3974 InputEvent* received = mWindow->consume();
3975 ASSERT_NE(nullptr, received);
3976 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3977 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3978 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3979 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003980 }
3981
3982private:
3983 sp<FakeWindowHandle> mWindow;
3984};
3985
3986TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003987 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3988 // filter. Without it, the event will no different from a regularly injected event, and the
3989 // injected device id will be overwritten.
3990 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3991 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003992}
3993
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003994TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003995 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003996 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3997 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3998}
3999
4000TEST_F(InputFilterInjectionPolicyTest,
4001 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4002 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4003 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4004 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004005}
4006
4007TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4008 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004009 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004010}
4011
chaviwfd6d3512019-03-25 13:23:49 -07004012class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004013 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004014 InputDispatcherTest::SetUp();
4015
Chris Yea209fde2020-07-22 13:54:51 -07004016 std::shared_ptr<FakeApplicationHandle> application =
4017 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004018 mUnfocusedWindow =
4019 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004020 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004021
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004022 mFocusedWindow =
4023 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4024 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004025
4026 // Set focused application.
4027 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004028 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004029
4030 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004031 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004032 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004033 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004034 }
4035
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004036 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004037 InputDispatcherTest::TearDown();
4038
4039 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004040 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004041 }
4042
4043protected:
4044 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004045 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004046 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004047};
4048
4049// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4050// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4051// the onPointerDownOutsideFocus callback.
4052TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004053 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004054 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4055 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004056 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004057 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004058
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004059 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004060 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4061}
4062
4063// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4064// DOWN on the window that doesn't have focus. Ensure no window received the
4065// onPointerDownOutsideFocus callback.
4066TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004067 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004068 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004069 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004070 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004071
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004072 ASSERT_TRUE(mDispatcher->waitForIdle());
4073 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004074}
4075
4076// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4077// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4078TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004079 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4080 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004081 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004082 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004083
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004084 ASSERT_TRUE(mDispatcher->waitForIdle());
4085 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004086}
4087
4088// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4089// DOWN on the window that already has focus. Ensure no window received the
4090// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004091TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004092 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004093 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004094 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004095 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004096 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004097
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004098 ASSERT_TRUE(mDispatcher->waitForIdle());
4099 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004100}
4101
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004102// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4103// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4104TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4105 const MotionEvent event =
4106 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4107 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4108 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4109 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4110 .build();
4111 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4112 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4113 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4114
4115 ASSERT_TRUE(mDispatcher->waitForIdle());
4116 mFakePolicy->assertOnPointerDownWasNotCalled();
4117 // Ensure that the unfocused window did not receive any FOCUS events.
4118 mUnfocusedWindow->assertNoEvents();
4119}
4120
chaviwaf87b3e2019-10-01 16:59:28 -07004121// These tests ensures we can send touch events to a single client when there are multiple input
4122// windows that point to the same client token.
4123class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4124 virtual void SetUp() override {
4125 InputDispatcherTest::SetUp();
4126
Chris Yea209fde2020-07-22 13:54:51 -07004127 std::shared_ptr<FakeApplicationHandle> application =
4128 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004129 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4130 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004131 mWindow1->setFrame(Rect(0, 0, 100, 100));
4132
4133 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4134 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004135 mWindow2->setFrame(Rect(100, 100, 200, 200));
4136
Arthur Hung72d8dc32020-03-28 00:48:39 +00004137 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004138 }
4139
4140protected:
4141 sp<FakeWindowHandle> mWindow1;
4142 sp<FakeWindowHandle> mWindow2;
4143
4144 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004145 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004146 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4147 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004148 }
4149
4150 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4151 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004152 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004153 InputEvent* event = window->consume();
4154
4155 ASSERT_NE(nullptr, event) << name.c_str()
4156 << ": consumer should have returned non-NULL event.";
4157
4158 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4159 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4160 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4161
4162 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004163 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004164
4165 for (size_t i = 0; i < points.size(); i++) {
4166 float expectedX = points[i].x;
4167 float expectedY = points[i].y;
4168
4169 EXPECT_EQ(expectedX, motionEvent.getX(i))
4170 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4171 << ", got " << motionEvent.getX(i);
4172 EXPECT_EQ(expectedY, motionEvent.getY(i))
4173 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4174 << ", got " << motionEvent.getY(i);
4175 }
4176 }
chaviw9eaa22c2020-07-01 16:21:27 -07004177
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004178 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004179 std::vector<PointF> expectedPoints) {
4180 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4181 ADISPLAY_ID_DEFAULT, touchedPoints);
4182 mDispatcher->notifyMotion(&motionArgs);
4183
4184 // Always consume from window1 since it's the window that has the InputReceiver
4185 consumeMotionEvent(mWindow1, action, expectedPoints);
4186 }
chaviwaf87b3e2019-10-01 16:59:28 -07004187};
4188
4189TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
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
4195 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004196 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004197
4198 // Touch Window 2
4199 touchedPoint = {150, 150};
4200 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004201 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004202}
4203
chaviw9eaa22c2020-07-01 16:21:27 -07004204TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4205 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004206 mWindow2->setWindowScale(0.5f, 0.5f);
4207
4208 // Touch Window 1
4209 PointF touchedPoint = {10, 10};
4210 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004211 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004212 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004213 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004214
4215 // Touch Window 2
4216 touchedPoint = {150, 150};
4217 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004218 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4219 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004220
chaviw9eaa22c2020-07-01 16:21:27 -07004221 // Update the transform so rotation is set
4222 mWindow2->setWindowTransform(0, -1, 1, 0);
4223 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4224 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004225}
4226
chaviw9eaa22c2020-07-01 16:21:27 -07004227TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004228 mWindow2->setWindowScale(0.5f, 0.5f);
4229
4230 // Touch Window 1
4231 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4232 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004233 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004234
4235 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004236 touchedPoints.push_back(PointF{150, 150});
4237 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004238 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004239
chaviw9eaa22c2020-07-01 16:21:27 -07004240 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004241 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004242 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004243
chaviw9eaa22c2020-07-01 16:21:27 -07004244 // Update the transform so rotation is set for Window 2
4245 mWindow2->setWindowTransform(0, -1, 1, 0);
4246 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004247 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004248}
4249
chaviw9eaa22c2020-07-01 16:21:27 -07004250TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004251 mWindow2->setWindowScale(0.5f, 0.5f);
4252
4253 // Touch Window 1
4254 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4255 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004256 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004257
4258 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004259 touchedPoints.push_back(PointF{150, 150});
4260 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004261
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004262 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004263
4264 // Move both windows
4265 touchedPoints = {{20, 20}, {175, 175}};
4266 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4267 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4268
chaviw9eaa22c2020-07-01 16:21:27 -07004269 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004270
chaviw9eaa22c2020-07-01 16:21:27 -07004271 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004272 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004273 expectedPoints.pop_back();
4274
4275 // Touch Window 2
4276 mWindow2->setWindowTransform(0, -1, 1, 0);
4277 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004278 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004279
4280 // Move both windows
4281 touchedPoints = {{20, 20}, {175, 175}};
4282 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4283 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4284
4285 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004286}
4287
4288TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4289 mWindow1->setWindowScale(0.5f, 0.5f);
4290
4291 // Touch Window 1
4292 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4293 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004294 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004295
4296 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004297 touchedPoints.push_back(PointF{150, 150});
4298 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004299
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004300 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004301
4302 // Move both windows
4303 touchedPoints = {{20, 20}, {175, 175}};
4304 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4305 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4306
chaviw9eaa22c2020-07-01 16:21:27 -07004307 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004308}
4309
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004310class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4311 virtual void SetUp() override {
4312 InputDispatcherTest::SetUp();
4313
Chris Yea209fde2020-07-22 13:54:51 -07004314 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004315 mApplication->setDispatchingTimeout(20ms);
4316 mWindow =
4317 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4318 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004319 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004320 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004321
4322 // Set focused application.
4323 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4324
4325 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004326 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004327 mWindow->consumeFocusEvent(true);
4328 }
4329
4330 virtual void TearDown() override {
4331 InputDispatcherTest::TearDown();
4332 mWindow.clear();
4333 }
4334
4335protected:
Chris Yea209fde2020-07-22 13:54:51 -07004336 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004337 sp<FakeWindowHandle> mWindow;
4338 static constexpr PointF WINDOW_LOCATION = {20, 20};
4339
4340 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004341 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004342 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4343 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004344 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004345 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4346 WINDOW_LOCATION));
4347 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004348
4349 sp<FakeWindowHandle> addSpyWindow() {
4350 sp<FakeWindowHandle> spy =
4351 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4352 spy->setTrustedOverlay(true);
4353 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004354 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004355 spy->setDispatchingTimeout(30ms);
4356 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4357 return spy;
4358 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004359};
4360
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004361// Send a tap and respond, which should not cause an ANR.
4362TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4363 tapOnWindow();
4364 mWindow->consumeMotionDown();
4365 mWindow->consumeMotionUp();
4366 ASSERT_TRUE(mDispatcher->waitForIdle());
4367 mFakePolicy->assertNotifyAnrWasNotCalled();
4368}
4369
4370// Send a regular key and respond, which should not cause an ANR.
4371TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004372 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004373 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4374 ASSERT_TRUE(mDispatcher->waitForIdle());
4375 mFakePolicy->assertNotifyAnrWasNotCalled();
4376}
4377
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004378TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4379 mWindow->setFocusable(false);
4380 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4381 mWindow->consumeFocusEvent(false);
4382
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004383 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004384 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004385 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4386 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004387 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004388 // Key will not go to window because we have no focused window.
4389 // The 'no focused window' ANR timer should start instead.
4390
4391 // Now, the focused application goes away.
4392 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4393 // The key should get dropped and there should be no ANR.
4394
4395 ASSERT_TRUE(mDispatcher->waitForIdle());
4396 mFakePolicy->assertNotifyAnrWasNotCalled();
4397}
4398
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004399// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004400// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4401// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004402TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004403 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004404 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4405 WINDOW_LOCATION));
4406
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004407 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4408 ASSERT_TRUE(sequenceNum);
4409 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004410 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004411
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004412 mWindow->finishEvent(*sequenceNum);
4413 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4414 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004415 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004416 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004417}
4418
4419// Send a key to the app and have the app not respond right away.
4420TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4421 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004422 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004423 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4424 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004425 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004426 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004427 ASSERT_TRUE(mDispatcher->waitForIdle());
4428}
4429
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004430// We have a focused application, but no focused window
4431TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004432 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004433 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4434 mWindow->consumeFocusEvent(false);
4435
4436 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004437 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004438 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4439 WINDOW_LOCATION));
4440 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4441 mDispatcher->waitForIdle();
4442 mFakePolicy->assertNotifyAnrWasNotCalled();
4443
4444 // Once a focused event arrives, we get an ANR for this application
4445 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4446 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004447 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004448 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004449 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004450 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004451 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004452 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004453 ASSERT_TRUE(mDispatcher->waitForIdle());
4454}
4455
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004456/**
4457 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4458 * there will not be an ANR.
4459 */
4460TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4461 mWindow->setFocusable(false);
4462 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4463 mWindow->consumeFocusEvent(false);
4464
4465 KeyEvent event;
4466 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4467 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4468
4469 // Define a valid key down event that is stale (too old).
4470 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4471 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4472 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4473
4474 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4475
4476 InputEventInjectionResult result =
4477 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
4478 InputEventInjectionSync::WAIT_FOR_RESULT,
4479 INJECT_EVENT_TIMEOUT, policyFlags);
4480 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4481 << "Injection should fail because the event is stale";
4482
4483 ASSERT_TRUE(mDispatcher->waitForIdle());
4484 mFakePolicy->assertNotifyAnrWasNotCalled();
4485 mWindow->assertNoEvents();
4486}
4487
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004488// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004489// Make sure that we don't notify policy twice about the same ANR.
4490TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004491 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004492 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4493 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004494
4495 // Once a focused event arrives, we get an ANR for this application
4496 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4497 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004498 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004499 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004500 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004501 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004502 const std::chrono::duration appTimeout =
4503 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004504 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004505
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004506 std::this_thread::sleep_for(appTimeout);
4507 // ANR should not be raised again. It is up to policy to do that if it desires.
4508 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004509
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004510 // If we now get a focused window, the ANR should stop, but the policy handles that via
4511 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004512 ASSERT_TRUE(mDispatcher->waitForIdle());
4513}
4514
4515// We have a focused application, but no focused window
4516TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004517 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004518 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4519 mWindow->consumeFocusEvent(false);
4520
4521 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004522 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004523 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004524 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4525 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004526
4527 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004528 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004529
4530 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004531 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004532 ASSERT_TRUE(mDispatcher->waitForIdle());
4533 mWindow->assertNoEvents();
4534}
4535
4536/**
4537 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4538 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4539 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4540 * the ANR mechanism should still work.
4541 *
4542 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4543 * DOWN event, while not responding on the second one.
4544 */
4545TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4546 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4547 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4548 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4549 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4550 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004551 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004552
4553 // Now send ACTION_UP, with identical timestamp
4554 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4555 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4556 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4557 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004558 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004559
4560 // We have now sent down and up. Let's consume first event and then ANR on the second.
4561 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4562 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004563 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004564}
4565
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004566// A spy window can receive an ANR
4567TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4568 sp<FakeWindowHandle> spy = addSpyWindow();
4569
4570 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4571 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4572 WINDOW_LOCATION));
4573 mWindow->consumeMotionDown();
4574
4575 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4576 ASSERT_TRUE(sequenceNum);
4577 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004578 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004579
4580 spy->finishEvent(*sequenceNum);
4581 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4582 0 /*flags*/);
4583 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004584 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004585}
4586
4587// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004588// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004589TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4590 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004591
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004592 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4593 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004594 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004595 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004596
4597 // Stuck on the ACTION_UP
4598 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004599 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004600
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004601 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004602 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004603 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4604 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004605
4606 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4607 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004608 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004609 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004610 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004611}
4612
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004613// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004614// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004615TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4616 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004617
4618 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004619 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4620 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004621
4622 mWindow->consumeMotionDown();
4623 // Stuck on the ACTION_UP
4624 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004625 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004626
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004627 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004628 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004629 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4630 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004631
4632 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4633 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004634 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004635 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004636 spy->assertNoEvents();
4637}
4638
4639TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4640 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4641
4642 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4643
4644 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4645 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4646 WINDOW_LOCATION));
4647
4648 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4649 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4650 ASSERT_TRUE(consumeSeq);
4651
Prabir Pradhanedd96402022-02-15 01:46:16 -08004652 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004653
4654 monitor.finishEvent(*consumeSeq);
4655 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4656
4657 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004658 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004659}
4660
4661// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4662// process events, you don't get an anr. When the window later becomes unresponsive again, you
4663// get an ANR again.
4664// 1. tap -> block on ACTION_UP -> receive ANR
4665// 2. consume all pending events (= queue becomes healthy again)
4666// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4667TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4668 tapOnWindow();
4669
4670 mWindow->consumeMotionDown();
4671 // Block on ACTION_UP
4672 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004673 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004674 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4675 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004676 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004677 mWindow->assertNoEvents();
4678
4679 tapOnWindow();
4680 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004681 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004682 mWindow->consumeMotionUp();
4683
4684 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004685 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004686 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004687 mWindow->assertNoEvents();
4688}
4689
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004690// If a connection remains unresponsive for a while, make sure policy is only notified once about
4691// it.
4692TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004693 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004694 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4695 WINDOW_LOCATION));
4696
4697 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004698 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004699 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004700 // 'notifyConnectionUnresponsive' should only be called once per connection
4701 mFakePolicy->assertNotifyAnrWasNotCalled();
4702 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004703 mWindow->consumeMotionDown();
4704 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4705 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4706 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004707 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004708 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004709 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004710}
4711
4712/**
4713 * If a window is processing a motion event, and then a key event comes in, the key event should
4714 * not to to the focused window until the motion is processed.
4715 *
4716 * Warning!!!
4717 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4718 * and the injection timeout that we specify when injecting the key.
4719 * We must have the injection timeout (10ms) be smaller than
4720 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4721 *
4722 * If that value changes, this test should also change.
4723 */
4724TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4725 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4726 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4727
4728 tapOnWindow();
4729 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4730 ASSERT_TRUE(downSequenceNum);
4731 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4732 ASSERT_TRUE(upSequenceNum);
4733 // Don't finish the events yet, and send a key
4734 // Injection will "succeed" because we will eventually give up and send the key to the focused
4735 // window even if motions are still being processed. But because the injection timeout is short,
4736 // we will receive INJECTION_TIMED_OUT as the result.
4737
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004738 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004739 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004740 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4741 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004742 // Key will not be sent to the window, yet, because the window is still processing events
4743 // and the key remains pending, waiting for the touch events to be processed
4744 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4745 ASSERT_FALSE(keySequenceNum);
4746
4747 std::this_thread::sleep_for(500ms);
4748 // if we wait long enough though, dispatcher will give up, and still send the key
4749 // to the focused window, even though we have not yet finished the motion event
4750 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4751 mWindow->finishEvent(*downSequenceNum);
4752 mWindow->finishEvent(*upSequenceNum);
4753}
4754
4755/**
4756 * If a window is processing a motion event, and then a key event comes in, the key event should
4757 * not go to the focused window until the motion is processed.
4758 * If then a new motion comes in, then the pending key event should be going to the currently
4759 * focused window right away.
4760 */
4761TEST_F(InputDispatcherSingleWindowAnr,
4762 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4763 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4764 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4765
4766 tapOnWindow();
4767 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4768 ASSERT_TRUE(downSequenceNum);
4769 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4770 ASSERT_TRUE(upSequenceNum);
4771 // Don't finish the events yet, and send a key
4772 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004773 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004774 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004775 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004776 // At this point, key is still pending, and should not be sent to the application yet.
4777 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4778 ASSERT_FALSE(keySequenceNum);
4779
4780 // Now tap down again. It should cause the pending key to go to the focused window right away.
4781 tapOnWindow();
4782 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4783 // the other events yet. We can finish events in any order.
4784 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4785 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4786 mWindow->consumeMotionDown();
4787 mWindow->consumeMotionUp();
4788 mWindow->assertNoEvents();
4789}
4790
4791class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4792 virtual void SetUp() override {
4793 InputDispatcherTest::SetUp();
4794
Chris Yea209fde2020-07-22 13:54:51 -07004795 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004796 mApplication->setDispatchingTimeout(10ms);
4797 mUnfocusedWindow =
4798 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4799 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004800 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004801 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004802
4803 mFocusedWindow =
4804 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004805 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004806 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004807
4808 // Set focused application.
4809 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004810 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004811
4812 // Expect one focus window exist in display.
4813 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004814 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004815 mFocusedWindow->consumeFocusEvent(true);
4816 }
4817
4818 virtual void TearDown() override {
4819 InputDispatcherTest::TearDown();
4820
4821 mUnfocusedWindow.clear();
4822 mFocusedWindow.clear();
4823 }
4824
4825protected:
Chris Yea209fde2020-07-22 13:54:51 -07004826 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004827 sp<FakeWindowHandle> mUnfocusedWindow;
4828 sp<FakeWindowHandle> mFocusedWindow;
4829 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4830 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4831 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4832
4833 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4834
4835 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4836
4837private:
4838 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004839 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004840 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4841 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004842 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004843 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4844 location));
4845 }
4846};
4847
4848// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4849// should be ANR'd first.
4850TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004851 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004852 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4853 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004854 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004855 mFocusedWindow->consumeMotionDown();
4856 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4857 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4858 // We consumed all events, so no ANR
4859 ASSERT_TRUE(mDispatcher->waitForIdle());
4860 mFakePolicy->assertNotifyAnrWasNotCalled();
4861
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004862 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004863 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4864 FOCUSED_WINDOW_LOCATION));
4865 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4866 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004867
4868 const std::chrono::duration timeout =
4869 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004870 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004871 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4872 // sequence to make it consistent
4873 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004874 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004875 mFocusedWindow->consumeMotionDown();
4876 // This cancel is generated because the connection was unresponsive
4877 mFocusedWindow->consumeMotionCancel();
4878 mFocusedWindow->assertNoEvents();
4879 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004880 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004881 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
4882 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004883 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004884}
4885
4886// If we have 2 windows with identical timeouts that are both unresponsive,
4887// it doesn't matter which order they should have ANR.
4888// But we should receive ANR for both.
4889TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4890 // Set the timeout for unfocused window to match the focused window
4891 mUnfocusedWindow->setDispatchingTimeout(10ms);
4892 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4893
4894 tapOnFocusedWindow();
4895 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08004896 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
4897 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
4898 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004899
4900 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004901 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4902 mFocusedWindow->getToken() == anrConnectionToken2);
4903 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4904 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004905
4906 ASSERT_TRUE(mDispatcher->waitForIdle());
4907 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004908
4909 mFocusedWindow->consumeMotionDown();
4910 mFocusedWindow->consumeMotionUp();
4911 mUnfocusedWindow->consumeMotionOutside();
4912
Prabir Pradhanedd96402022-02-15 01:46:16 -08004913 sp<IBinder> responsiveToken1, responsiveToken2;
4914 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
4915 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004916
4917 // Both applications should be marked as responsive, in any order
4918 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4919 mFocusedWindow->getToken() == responsiveToken2);
4920 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4921 mUnfocusedWindow->getToken() == responsiveToken2);
4922 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004923}
4924
4925// If a window is already not responding, the second tap on the same window should be ignored.
4926// We should also log an error to account for the dropped event (not tested here).
4927// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4928TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4929 tapOnFocusedWindow();
4930 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4931 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4932 // Receive the events, but don't respond
4933 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4934 ASSERT_TRUE(downEventSequenceNum);
4935 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4936 ASSERT_TRUE(upEventSequenceNum);
4937 const std::chrono::duration timeout =
4938 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004939 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004940
4941 // Tap once again
4942 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004943 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004944 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4945 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004946 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004947 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4948 FOCUSED_WINDOW_LOCATION));
4949 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4950 // valid touch target
4951 mUnfocusedWindow->assertNoEvents();
4952
4953 // Consume the first tap
4954 mFocusedWindow->finishEvent(*downEventSequenceNum);
4955 mFocusedWindow->finishEvent(*upEventSequenceNum);
4956 ASSERT_TRUE(mDispatcher->waitForIdle());
4957 // The second tap did not go to the focused window
4958 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004959 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08004960 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
4961 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004962 mFakePolicy->assertNotifyAnrWasNotCalled();
4963}
4964
4965// If you tap outside of all windows, there will not be ANR
4966TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004967 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004968 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4969 LOCATION_OUTSIDE_ALL_WINDOWS));
4970 ASSERT_TRUE(mDispatcher->waitForIdle());
4971 mFakePolicy->assertNotifyAnrWasNotCalled();
4972}
4973
4974// Since the focused window is paused, tapping on it should not produce any events
4975TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4976 mFocusedWindow->setPaused(true);
4977 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4978
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004979 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004980 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4981 FOCUSED_WINDOW_LOCATION));
4982
4983 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4984 ASSERT_TRUE(mDispatcher->waitForIdle());
4985 // Should not ANR because the window is paused, and touches shouldn't go to it
4986 mFakePolicy->assertNotifyAnrWasNotCalled();
4987
4988 mFocusedWindow->assertNoEvents();
4989 mUnfocusedWindow->assertNoEvents();
4990}
4991
4992/**
4993 * If a window is processing a motion event, and then a key event comes in, the key event should
4994 * not to to the focused window until the motion is processed.
4995 * If a different window becomes focused at this time, the key should go to that window instead.
4996 *
4997 * Warning!!!
4998 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4999 * and the injection timeout that we specify when injecting the key.
5000 * We must have the injection timeout (10ms) be smaller than
5001 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5002 *
5003 * If that value changes, this test should also change.
5004 */
5005TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5006 // Set a long ANR timeout to prevent it from triggering
5007 mFocusedWindow->setDispatchingTimeout(2s);
5008 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5009
5010 tapOnUnfocusedWindow();
5011 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5012 ASSERT_TRUE(downSequenceNum);
5013 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5014 ASSERT_TRUE(upSequenceNum);
5015 // Don't finish the events yet, and send a key
5016 // Injection will succeed because we will eventually give up and send the key to the focused
5017 // window even if motions are still being processed.
5018
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005019 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005020 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005021 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5022 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005023 // Key will not be sent to the window, yet, because the window is still processing events
5024 // and the key remains pending, waiting for the touch events to be processed
5025 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5026 ASSERT_FALSE(keySequenceNum);
5027
5028 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005029 mFocusedWindow->setFocusable(false);
5030 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005031 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005032 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005033
5034 // Focus events should precede the key events
5035 mUnfocusedWindow->consumeFocusEvent(true);
5036 mFocusedWindow->consumeFocusEvent(false);
5037
5038 // Finish the tap events, which should unblock dispatcher
5039 mUnfocusedWindow->finishEvent(*downSequenceNum);
5040 mUnfocusedWindow->finishEvent(*upSequenceNum);
5041
5042 // Now that all queues are cleared and no backlog in the connections, the key event
5043 // can finally go to the newly focused "mUnfocusedWindow".
5044 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5045 mFocusedWindow->assertNoEvents();
5046 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005047 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005048}
5049
5050// When the touch stream is split across 2 windows, and one of them does not respond,
5051// then ANR should be raised and the touch should be canceled for the unresponsive window.
5052// The other window should not be affected by that.
5053TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5054 // Touch Window 1
5055 NotifyMotionArgs motionArgs =
5056 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5057 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5058 mDispatcher->notifyMotion(&motionArgs);
5059 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5060 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5061
5062 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005063 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5064 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005065 mDispatcher->notifyMotion(&motionArgs);
5066
5067 const std::chrono::duration timeout =
5068 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005069 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005070
5071 mUnfocusedWindow->consumeMotionDown();
5072 mFocusedWindow->consumeMotionDown();
5073 // Focused window may or may not receive ACTION_MOVE
5074 // But it should definitely receive ACTION_CANCEL due to the ANR
5075 InputEvent* event;
5076 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5077 ASSERT_TRUE(moveOrCancelSequenceNum);
5078 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5079 ASSERT_NE(nullptr, event);
5080 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5081 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5082 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5083 mFocusedWindow->consumeMotionCancel();
5084 } else {
5085 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5086 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005087 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005088 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5089 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005090
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005091 mUnfocusedWindow->assertNoEvents();
5092 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005093 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005094}
5095
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005096/**
5097 * If we have no focused window, and a key comes in, we start the ANR timer.
5098 * The focused application should add a focused window before the timer runs out to prevent ANR.
5099 *
5100 * If the user touches another application during this time, the key should be dropped.
5101 * Next, if a new focused window comes in, without toggling the focused application,
5102 * then no ANR should occur.
5103 *
5104 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5105 * but in some cases the policy may not update the focused application.
5106 */
5107TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5108 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5109 std::make_shared<FakeApplicationHandle>();
5110 focusedApplication->setDispatchingTimeout(60ms);
5111 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5112 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5113 mFocusedWindow->setFocusable(false);
5114
5115 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5116 mFocusedWindow->consumeFocusEvent(false);
5117
5118 // Send a key. The ANR timer should start because there is no focused window.
5119 // 'focusedApplication' will get blamed if this timer completes.
5120 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005121 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005122 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005123 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5124 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005125 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005126
5127 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5128 // then the injected touches won't cause the focused event to get dropped.
5129 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5130 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5131 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5132 // For this test, it means that the key would get delivered to the window once it becomes
5133 // focused.
5134 std::this_thread::sleep_for(10ms);
5135
5136 // Touch unfocused window. This should force the pending key to get dropped.
5137 NotifyMotionArgs motionArgs =
5138 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5139 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5140 mDispatcher->notifyMotion(&motionArgs);
5141
5142 // We do not consume the motion right away, because that would require dispatcher to first
5143 // process (== drop) the key event, and by that time, ANR will be raised.
5144 // Set the focused window first.
5145 mFocusedWindow->setFocusable(true);
5146 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5147 setFocusedWindow(mFocusedWindow);
5148 mFocusedWindow->consumeFocusEvent(true);
5149 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5150 // to another application. This could be a bug / behaviour in the policy.
5151
5152 mUnfocusedWindow->consumeMotionDown();
5153
5154 ASSERT_TRUE(mDispatcher->waitForIdle());
5155 // Should not ANR because we actually have a focused window. It was just added too slowly.
5156 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5157}
5158
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005159// These tests ensure we cannot send touch events to a window that's positioned behind a window
5160// that has feature NO_INPUT_CHANNEL.
5161// Layout:
5162// Top (closest to user)
5163// mNoInputWindow (above all windows)
5164// mBottomWindow
5165// Bottom (furthest from user)
5166class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5167 virtual void SetUp() override {
5168 InputDispatcherTest::SetUp();
5169
5170 mApplication = std::make_shared<FakeApplicationHandle>();
5171 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5172 "Window without input channel", ADISPLAY_ID_DEFAULT,
5173 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5174
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005175 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005176 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5177 // It's perfectly valid for this window to not have an associated input channel
5178
5179 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5180 ADISPLAY_ID_DEFAULT);
5181 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5182
5183 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5184 }
5185
5186protected:
5187 std::shared_ptr<FakeApplicationHandle> mApplication;
5188 sp<FakeWindowHandle> mNoInputWindow;
5189 sp<FakeWindowHandle> mBottomWindow;
5190};
5191
5192TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5193 PointF touchedPoint = {10, 10};
5194
5195 NotifyMotionArgs motionArgs =
5196 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5197 ADISPLAY_ID_DEFAULT, {touchedPoint});
5198 mDispatcher->notifyMotion(&motionArgs);
5199
5200 mNoInputWindow->assertNoEvents();
5201 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5202 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5203 // and therefore should prevent mBottomWindow from receiving touches
5204 mBottomWindow->assertNoEvents();
5205}
5206
5207/**
5208 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5209 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5210 */
5211TEST_F(InputDispatcherMultiWindowOcclusionTests,
5212 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5213 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5214 "Window with input channel and NO_INPUT_CHANNEL",
5215 ADISPLAY_ID_DEFAULT);
5216
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005217 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005218 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5219 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5220
5221 PointF touchedPoint = {10, 10};
5222
5223 NotifyMotionArgs motionArgs =
5224 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5225 ADISPLAY_ID_DEFAULT, {touchedPoint});
5226 mDispatcher->notifyMotion(&motionArgs);
5227
5228 mNoInputWindow->assertNoEvents();
5229 mBottomWindow->assertNoEvents();
5230}
5231
Vishnu Nair958da932020-08-21 17:12:37 -07005232class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5233protected:
5234 std::shared_ptr<FakeApplicationHandle> mApp;
5235 sp<FakeWindowHandle> mWindow;
5236 sp<FakeWindowHandle> mMirror;
5237
5238 virtual void SetUp() override {
5239 InputDispatcherTest::SetUp();
5240 mApp = std::make_shared<FakeApplicationHandle>();
5241 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5242 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5243 mWindow->getToken());
5244 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5245 mWindow->setFocusable(true);
5246 mMirror->setFocusable(true);
5247 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5248 }
5249};
5250
5251TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5252 // Request focus on a mirrored window
5253 setFocusedWindow(mMirror);
5254
5255 // window gets focused
5256 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005257 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5258 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005259 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5260}
5261
5262// A focused & mirrored window remains focused only if the window and its mirror are both
5263// focusable.
5264TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5265 setFocusedWindow(mMirror);
5266
5267 // window gets focused
5268 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005269 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5270 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005271 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005272 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5273 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005274 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5275
5276 mMirror->setFocusable(false);
5277 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5278
5279 // window loses focus since one of the windows associated with the token in not focusable
5280 mWindow->consumeFocusEvent(false);
5281
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005282 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5283 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005284 mWindow->assertNoEvents();
5285}
5286
5287// A focused & mirrored window remains focused until the window and its mirror both become
5288// invisible.
5289TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5290 setFocusedWindow(mMirror);
5291
5292 // window gets focused
5293 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005294 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5295 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005296 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005297 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5298 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005299 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5300
5301 mMirror->setVisible(false);
5302 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5303
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005304 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5305 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005306 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005307 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5308 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005309 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5310
5311 mWindow->setVisible(false);
5312 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5313
5314 // window loses focus only after all windows associated with the token become invisible.
5315 mWindow->consumeFocusEvent(false);
5316
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005317 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5318 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005319 mWindow->assertNoEvents();
5320}
5321
5322// A focused & mirrored window remains focused until both windows are removed.
5323TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5324 setFocusedWindow(mMirror);
5325
5326 // window gets focused
5327 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005328 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5329 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005330 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005331 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5332 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005333 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5334
5335 // single window is removed but the window token remains focused
5336 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5337
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005338 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5339 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005340 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005341 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5342 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005343 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5344
5345 // Both windows are removed
5346 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5347 mWindow->consumeFocusEvent(false);
5348
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005349 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5350 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005351 mWindow->assertNoEvents();
5352}
5353
5354// Focus request can be pending until one window becomes visible.
5355TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5356 // Request focus on an invisible mirror.
5357 mWindow->setVisible(false);
5358 mMirror->setVisible(false);
5359 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5360 setFocusedWindow(mMirror);
5361
5362 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005363 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005364 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005365 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005366
5367 mMirror->setVisible(true);
5368 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5369
5370 // window gets focused
5371 mWindow->consumeFocusEvent(true);
5372 // window gets the pending key event
5373 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5374}
Prabir Pradhan99987712020-11-10 18:43:05 -08005375
5376class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5377protected:
5378 std::shared_ptr<FakeApplicationHandle> mApp;
5379 sp<FakeWindowHandle> mWindow;
5380 sp<FakeWindowHandle> mSecondWindow;
5381
5382 void SetUp() override {
5383 InputDispatcherTest::SetUp();
5384 mApp = std::make_shared<FakeApplicationHandle>();
5385 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5386 mWindow->setFocusable(true);
5387 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5388 mSecondWindow->setFocusable(true);
5389
5390 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5391 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5392
5393 setFocusedWindow(mWindow);
5394 mWindow->consumeFocusEvent(true);
5395 }
5396
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005397 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5398 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005399 mDispatcher->notifyPointerCaptureChanged(&args);
5400 }
5401
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005402 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5403 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005404 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005405 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5406 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005407 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005408 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005409 }
5410};
5411
5412TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5413 // Ensure that capture cannot be obtained for unfocused windows.
5414 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5415 mFakePolicy->assertSetPointerCaptureNotCalled();
5416 mSecondWindow->assertNoEvents();
5417
5418 // Ensure that capture can be enabled from the focus window.
5419 requestAndVerifyPointerCapture(mWindow, true);
5420
5421 // Ensure that capture cannot be disabled from a window that does not have capture.
5422 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5423 mFakePolicy->assertSetPointerCaptureNotCalled();
5424
5425 // Ensure that capture can be disabled from the window with capture.
5426 requestAndVerifyPointerCapture(mWindow, false);
5427}
5428
5429TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005430 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005431
5432 setFocusedWindow(mSecondWindow);
5433
5434 // Ensure that the capture disabled event was sent first.
5435 mWindow->consumeCaptureEvent(false);
5436 mWindow->consumeFocusEvent(false);
5437 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005438 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005439
5440 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005441 notifyPointerCaptureChanged({});
5442 notifyPointerCaptureChanged(request);
5443 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005444 mWindow->assertNoEvents();
5445 mSecondWindow->assertNoEvents();
5446 mFakePolicy->assertSetPointerCaptureNotCalled();
5447}
5448
5449TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005450 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005451
5452 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005453 notifyPointerCaptureChanged({});
5454 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005455
5456 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005457 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005458 mWindow->consumeCaptureEvent(false);
5459 mWindow->assertNoEvents();
5460}
5461
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005462TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5463 requestAndVerifyPointerCapture(mWindow, true);
5464
5465 // The first window loses focus.
5466 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005467 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005468 mWindow->consumeCaptureEvent(false);
5469
5470 // Request Pointer Capture from the second window before the notification from InputReader
5471 // arrives.
5472 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005473 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005474
5475 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005476 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005477
5478 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005479 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005480
5481 mSecondWindow->consumeFocusEvent(true);
5482 mSecondWindow->consumeCaptureEvent(true);
5483}
5484
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005485TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5486 // App repeatedly enables and disables capture.
5487 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5488 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5489 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5490 mFakePolicy->assertSetPointerCaptureCalled(false);
5491 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5492 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5493
5494 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5495 // first request is now stale, this should do nothing.
5496 notifyPointerCaptureChanged(firstRequest);
5497 mWindow->assertNoEvents();
5498
5499 // InputReader notifies that the second request was enabled.
5500 notifyPointerCaptureChanged(secondRequest);
5501 mWindow->consumeCaptureEvent(true);
5502}
5503
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005504class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5505protected:
5506 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005507
5508 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5509 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5510
5511 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5512 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5513
5514 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5515 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5516 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5517 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5518 MAXIMUM_OBSCURING_OPACITY);
5519
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005520 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005521 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005522 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005523
5524 sp<FakeWindowHandle> mTouchWindow;
5525
5526 virtual void SetUp() override {
5527 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005528 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005529 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5530 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5531 }
5532
5533 virtual void TearDown() override {
5534 InputDispatcherTest::TearDown();
5535 mTouchWindow.clear();
5536 }
5537
chaviw3277faf2021-05-19 16:45:23 -05005538 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5539 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005540 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005541 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005542 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005543 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005544 return window;
5545 }
5546
5547 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5548 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5549 sp<FakeWindowHandle> window =
5550 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5551 // Generate an arbitrary PID based on the UID
5552 window->setOwnerInfo(1777 + (uid % 10000), uid);
5553 return window;
5554 }
5555
5556 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5557 NotifyMotionArgs args =
5558 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5559 ADISPLAY_ID_DEFAULT, points);
5560 mDispatcher->notifyMotion(&args);
5561 }
5562};
5563
5564TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005565 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005566 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005567 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005568
5569 touch();
5570
5571 mTouchWindow->assertNoEvents();
5572}
5573
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005574TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005575 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5576 const sp<FakeWindowHandle>& w =
5577 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5578 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5579
5580 touch();
5581
5582 mTouchWindow->assertNoEvents();
5583}
5584
5585TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005586 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5587 const sp<FakeWindowHandle>& w =
5588 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5589 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5590
5591 touch();
5592
5593 w->assertNoEvents();
5594}
5595
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005596TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005597 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5598 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005599
5600 touch();
5601
5602 mTouchWindow->consumeAnyMotionDown();
5603}
5604
5605TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005606 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005607 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005608 w->setFrame(Rect(0, 0, 50, 50));
5609 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005610
5611 touch({PointF{100, 100}});
5612
5613 mTouchWindow->consumeAnyMotionDown();
5614}
5615
5616TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005617 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005618 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005619 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5620
5621 touch();
5622
5623 mTouchWindow->consumeAnyMotionDown();
5624}
5625
5626TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5627 const sp<FakeWindowHandle>& w =
5628 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5629 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005630
5631 touch();
5632
5633 mTouchWindow->consumeAnyMotionDown();
5634}
5635
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005636TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5637 const sp<FakeWindowHandle>& w =
5638 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5639 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5640
5641 touch();
5642
5643 w->assertNoEvents();
5644}
5645
5646/**
5647 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5648 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5649 * window, the occluding window will still receive ACTION_OUTSIDE event.
5650 */
5651TEST_F(InputDispatcherUntrustedTouchesTest,
5652 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5653 const sp<FakeWindowHandle>& w =
5654 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005655 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005656 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5657
5658 touch();
5659
5660 w->consumeMotionOutside();
5661}
5662
5663TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5664 const sp<FakeWindowHandle>& w =
5665 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005666 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005667 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5668
5669 touch();
5670
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005671 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005672}
5673
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005674TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005675 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005676 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5677 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005678 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5679
5680 touch();
5681
5682 mTouchWindow->consumeAnyMotionDown();
5683}
5684
5685TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5686 const sp<FakeWindowHandle>& w =
5687 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5688 MAXIMUM_OBSCURING_OPACITY);
5689 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005690
5691 touch();
5692
5693 mTouchWindow->consumeAnyMotionDown();
5694}
5695
5696TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005697 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005698 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5699 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005700 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5701
5702 touch();
5703
5704 mTouchWindow->assertNoEvents();
5705}
5706
5707TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5708 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5709 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005710 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5711 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005712 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005713 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5714 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005715 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5716
5717 touch();
5718
5719 mTouchWindow->assertNoEvents();
5720}
5721
5722TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5723 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5724 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005725 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5726 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005727 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005728 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5729 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005730 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5731
5732 touch();
5733
5734 mTouchWindow->consumeAnyMotionDown();
5735}
5736
5737TEST_F(InputDispatcherUntrustedTouchesTest,
5738 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5739 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005740 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5741 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005742 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005743 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5744 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005745 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5746
5747 touch();
5748
5749 mTouchWindow->consumeAnyMotionDown();
5750}
5751
5752TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5753 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005754 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5755 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005756 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005757 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5758 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005759 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005760
5761 touch();
5762
5763 mTouchWindow->assertNoEvents();
5764}
5765
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005766TEST_F(InputDispatcherUntrustedTouchesTest,
5767 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5768 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005769 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5770 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005771 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005772 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5773 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005774 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5775
5776 touch();
5777
5778 mTouchWindow->assertNoEvents();
5779}
5780
5781TEST_F(InputDispatcherUntrustedTouchesTest,
5782 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5783 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005784 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5785 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005786 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005787 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5788 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005789 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5790
5791 touch();
5792
5793 mTouchWindow->consumeAnyMotionDown();
5794}
5795
5796TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5797 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005798 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5799 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005800 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5801
5802 touch();
5803
5804 mTouchWindow->consumeAnyMotionDown();
5805}
5806
5807TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5808 const sp<FakeWindowHandle>& w =
5809 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5810 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5811
5812 touch();
5813
5814 mTouchWindow->consumeAnyMotionDown();
5815}
5816
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005817TEST_F(InputDispatcherUntrustedTouchesTest,
5818 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5819 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5820 const sp<FakeWindowHandle>& w =
5821 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5822 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5823
5824 touch();
5825
5826 mTouchWindow->assertNoEvents();
5827}
5828
5829TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5830 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5831 const sp<FakeWindowHandle>& w =
5832 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5833 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5834
5835 touch();
5836
5837 mTouchWindow->consumeAnyMotionDown();
5838}
5839
5840TEST_F(InputDispatcherUntrustedTouchesTest,
5841 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5842 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5843 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005844 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5845 OPACITY_ABOVE_THRESHOLD);
5846 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5847
5848 touch();
5849
5850 mTouchWindow->consumeAnyMotionDown();
5851}
5852
5853TEST_F(InputDispatcherUntrustedTouchesTest,
5854 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5855 const sp<FakeWindowHandle>& w1 =
5856 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5857 OPACITY_BELOW_THRESHOLD);
5858 const sp<FakeWindowHandle>& w2 =
5859 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5860 OPACITY_BELOW_THRESHOLD);
5861 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5862
5863 touch();
5864
5865 mTouchWindow->assertNoEvents();
5866}
5867
5868/**
5869 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5870 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5871 * (which alone would result in allowing touches) does not affect the blocking behavior.
5872 */
5873TEST_F(InputDispatcherUntrustedTouchesTest,
5874 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5875 const sp<FakeWindowHandle>& wB =
5876 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5877 OPACITY_BELOW_THRESHOLD);
5878 const sp<FakeWindowHandle>& wC =
5879 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5880 OPACITY_BELOW_THRESHOLD);
5881 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5882
5883 touch();
5884
5885 mTouchWindow->assertNoEvents();
5886}
5887
5888/**
5889 * This test is testing that a window from a different UID but with same application token doesn't
5890 * block the touch. Apps can share the application token for close UI collaboration for example.
5891 */
5892TEST_F(InputDispatcherUntrustedTouchesTest,
5893 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5894 const sp<FakeWindowHandle>& w =
5895 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5896 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005897 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5898
5899 touch();
5900
5901 mTouchWindow->consumeAnyMotionDown();
5902}
5903
arthurhungb89ccb02020-12-30 16:19:01 +08005904class InputDispatcherDragTests : public InputDispatcherTest {
5905protected:
5906 std::shared_ptr<FakeApplicationHandle> mApp;
5907 sp<FakeWindowHandle> mWindow;
5908 sp<FakeWindowHandle> mSecondWindow;
5909 sp<FakeWindowHandle> mDragWindow;
5910
5911 void SetUp() override {
5912 InputDispatcherTest::SetUp();
5913 mApp = std::make_shared<FakeApplicationHandle>();
5914 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5915 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005916
5917 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5918 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005919
5920 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5921 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5922 }
5923
5924 // Start performing drag, we will create a drag window and transfer touch to it.
5925 void performDrag() {
5926 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5927 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5928 {50, 50}))
5929 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5930
5931 // Window should receive motion event.
5932 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5933
5934 // The drag window covers the entire display
5935 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5936 mDispatcher->setInputWindows(
5937 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5938
5939 // Transfer touch focus to the drag window
5940 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5941 true /* isDragDrop */);
5942 mWindow->consumeMotionCancel();
5943 mDragWindow->consumeMotionDown();
5944 }
arthurhung6d4bed92021-03-17 11:59:33 +08005945
5946 // Start performing drag, we will create a drag window and transfer touch to it.
5947 void performStylusDrag() {
5948 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5949 injectMotionEvent(mDispatcher,
5950 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5951 AINPUT_SOURCE_STYLUS)
5952 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5953 .pointer(PointerBuilder(0,
5954 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5955 .x(50)
5956 .y(50))
5957 .build()));
5958 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5959
5960 // The drag window covers the entire display
5961 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5962 mDispatcher->setInputWindows(
5963 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5964
5965 // Transfer touch focus to the drag window
5966 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5967 true /* isDragDrop */);
5968 mWindow->consumeMotionCancel();
5969 mDragWindow->consumeMotionDown();
5970 }
arthurhungb89ccb02020-12-30 16:19:01 +08005971};
5972
5973TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5974 performDrag();
5975
5976 // Move on window.
5977 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5978 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5979 ADISPLAY_ID_DEFAULT, {50, 50}))
5980 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5981 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5982 mWindow->consumeDragEvent(false, 50, 50);
5983 mSecondWindow->assertNoEvents();
5984
5985 // Move to another window.
5986 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5987 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5988 ADISPLAY_ID_DEFAULT, {150, 50}))
5989 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5990 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5991 mWindow->consumeDragEvent(true, 150, 50);
5992 mSecondWindow->consumeDragEvent(false, 50, 50);
5993
5994 // Move back to original window.
5995 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5996 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5997 ADISPLAY_ID_DEFAULT, {50, 50}))
5998 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5999 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6000 mWindow->consumeDragEvent(false, 50, 50);
6001 mSecondWindow->consumeDragEvent(true, -50, 50);
6002
6003 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6004 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6005 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6006 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6007 mWindow->assertNoEvents();
6008 mSecondWindow->assertNoEvents();
6009}
6010
arthurhungf452d0b2021-01-06 00:19:52 +08006011TEST_F(InputDispatcherDragTests, DragAndDrop) {
6012 performDrag();
6013
6014 // Move on window.
6015 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6016 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6017 ADISPLAY_ID_DEFAULT, {50, 50}))
6018 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6019 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6020 mWindow->consumeDragEvent(false, 50, 50);
6021 mSecondWindow->assertNoEvents();
6022
6023 // Move to another window.
6024 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6025 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6026 ADISPLAY_ID_DEFAULT, {150, 50}))
6027 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6028 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6029 mWindow->consumeDragEvent(true, 150, 50);
6030 mSecondWindow->consumeDragEvent(false, 50, 50);
6031
6032 // drop to another window.
6033 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6034 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6035 {150, 50}))
6036 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6037 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6038 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6039 mWindow->assertNoEvents();
6040 mSecondWindow->assertNoEvents();
6041}
6042
arthurhung6d4bed92021-03-17 11:59:33 +08006043TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6044 performStylusDrag();
6045
6046 // Move on window and keep button pressed.
6047 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6048 injectMotionEvent(mDispatcher,
6049 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6050 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6051 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6052 .x(50)
6053 .y(50))
6054 .build()))
6055 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6056 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6057 mWindow->consumeDragEvent(false, 50, 50);
6058 mSecondWindow->assertNoEvents();
6059
6060 // Move to another window and release button, expect to drop item.
6061 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6062 injectMotionEvent(mDispatcher,
6063 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6064 .buttonState(0)
6065 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6066 .x(150)
6067 .y(50))
6068 .build()))
6069 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6070 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6071 mWindow->assertNoEvents();
6072 mSecondWindow->assertNoEvents();
6073 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6074
6075 // nothing to the window.
6076 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6077 injectMotionEvent(mDispatcher,
6078 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6079 .buttonState(0)
6080 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6081 .x(150)
6082 .y(50))
6083 .build()))
6084 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6085 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6086 mWindow->assertNoEvents();
6087 mSecondWindow->assertNoEvents();
6088}
6089
Arthur Hung6d0571e2021-04-09 20:18:16 +08006090TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6091 performDrag();
6092
6093 // Set second window invisible.
6094 mSecondWindow->setVisible(false);
6095 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6096
6097 // Move on window.
6098 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6099 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6100 ADISPLAY_ID_DEFAULT, {50, 50}))
6101 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6102 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6103 mWindow->consumeDragEvent(false, 50, 50);
6104 mSecondWindow->assertNoEvents();
6105
6106 // Move to another window.
6107 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6108 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6109 ADISPLAY_ID_DEFAULT, {150, 50}))
6110 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6111 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6112 mWindow->consumeDragEvent(true, 150, 50);
6113 mSecondWindow->assertNoEvents();
6114
6115 // drop to another window.
6116 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6117 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6118 {150, 50}))
6119 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6120 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6121 mFakePolicy->assertDropTargetEquals(nullptr);
6122 mWindow->assertNoEvents();
6123 mSecondWindow->assertNoEvents();
6124}
6125
Vishnu Nair062a8672021-09-03 16:07:44 -07006126class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6127
6128TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6129 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6130 sp<FakeWindowHandle> window =
6131 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006132 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006133 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6134 window->setFocusable(true);
6135 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6136 setFocusedWindow(window);
6137 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6138
6139 // With the flag set, window should not get any input
6140 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6141 mDispatcher->notifyKey(&keyArgs);
6142 window->assertNoEvents();
6143
6144 NotifyMotionArgs motionArgs =
6145 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6146 ADISPLAY_ID_DEFAULT);
6147 mDispatcher->notifyMotion(&motionArgs);
6148 window->assertNoEvents();
6149
6150 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006151 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006152 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6153
6154 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6155 mDispatcher->notifyKey(&keyArgs);
6156 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6157
6158 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6159 ADISPLAY_ID_DEFAULT);
6160 mDispatcher->notifyMotion(&motionArgs);
6161 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6162 window->assertNoEvents();
6163}
6164
6165TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6166 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6167 std::make_shared<FakeApplicationHandle>();
6168 sp<FakeWindowHandle> obscuringWindow =
6169 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6170 ADISPLAY_ID_DEFAULT);
6171 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6172 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006173 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006174 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6175 sp<FakeWindowHandle> window =
6176 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006177 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006178 window->setOwnerInfo(222, 222);
6179 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6180 window->setFocusable(true);
6181 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6182 setFocusedWindow(window);
6183 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6184
6185 // With the flag set, window should not get any input
6186 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6187 mDispatcher->notifyKey(&keyArgs);
6188 window->assertNoEvents();
6189
6190 NotifyMotionArgs motionArgs =
6191 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6192 ADISPLAY_ID_DEFAULT);
6193 mDispatcher->notifyMotion(&motionArgs);
6194 window->assertNoEvents();
6195
6196 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006197 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006198 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6199
6200 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6201 mDispatcher->notifyKey(&keyArgs);
6202 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6203
6204 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6205 ADISPLAY_ID_DEFAULT);
6206 mDispatcher->notifyMotion(&motionArgs);
6207 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6208 window->assertNoEvents();
6209}
6210
6211TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6212 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6213 std::make_shared<FakeApplicationHandle>();
6214 sp<FakeWindowHandle> obscuringWindow =
6215 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6216 ADISPLAY_ID_DEFAULT);
6217 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6218 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006219 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006220 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6221 sp<FakeWindowHandle> window =
6222 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006223 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006224 window->setOwnerInfo(222, 222);
6225 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6226 window->setFocusable(true);
6227 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6228 setFocusedWindow(window);
6229 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6230
6231 // With the flag set, window should not get any input
6232 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6233 mDispatcher->notifyKey(&keyArgs);
6234 window->assertNoEvents();
6235
6236 NotifyMotionArgs motionArgs =
6237 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6238 ADISPLAY_ID_DEFAULT);
6239 mDispatcher->notifyMotion(&motionArgs);
6240 window->assertNoEvents();
6241
6242 // When the window is no longer obscured because it went on top, it should get input
6243 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6244
6245 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6246 mDispatcher->notifyKey(&keyArgs);
6247 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6248
6249 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6250 ADISPLAY_ID_DEFAULT);
6251 mDispatcher->notifyMotion(&motionArgs);
6252 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6253 window->assertNoEvents();
6254}
6255
Antonio Kantekf16f2832021-09-28 04:39:20 +00006256class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6257protected:
6258 std::shared_ptr<FakeApplicationHandle> mApp;
6259 sp<FakeWindowHandle> mWindow;
6260 sp<FakeWindowHandle> mSecondWindow;
6261
6262 void SetUp() override {
6263 InputDispatcherTest::SetUp();
6264
6265 mApp = std::make_shared<FakeApplicationHandle>();
6266 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6267 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006268 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006269 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6270 mSecondWindow->setFocusable(true);
6271
6272 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6273 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006274 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006275
6276 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
6277 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, INJECTOR_PID,
6278 INJECTOR_UID, /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006279 }
6280
Antonio Kantekea47acb2021-12-23 12:41:25 -08006281 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006282 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006283 mWindow->consumeTouchModeEvent(inTouchMode);
6284 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6285 }
6286};
6287
Antonio Kantek26defcf2022-02-08 01:12:27 +00006288TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006289 const WindowInfo& windowInfo = *mWindow->getInfo();
6290 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6291 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006292}
6293
Antonio Kantek26defcf2022-02-08 01:12:27 +00006294TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6295 const WindowInfo& windowInfo = *mWindow->getInfo();
6296 int32_t ownerPid = windowInfo.ownerPid;
6297 int32_t ownerUid = windowInfo.ownerUid;
6298 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6299 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6300 ownerUid, /* hasPermission */ false));
6301 mWindow->assertNoEvents();
6302 mSecondWindow->assertNoEvents();
6303}
6304
6305TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6306 const WindowInfo& windowInfo = *mWindow->getInfo();
6307 int32_t ownerPid = windowInfo.ownerPid;
6308 int32_t ownerUid = windowInfo.ownerUid;
6309 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6310 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6311 /* hasPermission */ true);
6312}
6313
Antonio Kantekf16f2832021-09-28 04:39:20 +00006314TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006315 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006316 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6317 windowInfo.ownerPid, windowInfo.ownerUid,
6318 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006319 mWindow->assertNoEvents();
6320 mSecondWindow->assertNoEvents();
6321}
6322
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006323class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6324public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006325 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006326 std::shared_ptr<FakeApplicationHandle> application =
6327 std::make_shared<FakeApplicationHandle>();
6328 std::string name = "Fake Spy ";
6329 name += std::to_string(mSpyCount++);
6330 sp<FakeWindowHandle> spy =
6331 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006332 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006333 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006334 return spy;
6335 }
6336
6337 sp<FakeWindowHandle> createForeground() {
6338 std::shared_ptr<FakeApplicationHandle> application =
6339 std::make_shared<FakeApplicationHandle>();
6340 sp<FakeWindowHandle> window =
6341 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006342 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006343 return window;
6344 }
6345
6346private:
6347 int mSpyCount{0};
6348};
6349
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006350using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006351/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006352 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6353 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006354TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6355 ScopedSilentDeath _silentDeath;
6356
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006357 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006358 spy->setTrustedOverlay(false);
6359 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6360 ".* not a trusted overlay");
6361}
6362
6363/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006364 * Input injection into a display with a spy window but no foreground windows should succeed.
6365 */
6366TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006367 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006368 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6369
6370 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6371 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6372 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6373 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6374}
6375
6376/**
6377 * Verify the order in which different input windows receive events. The touched foreground window
6378 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6379 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6380 * receive events before ones belows it.
6381 *
6382 * Here, we set up a scenario with four windows in the following Z order from the top:
6383 * spy1, spy2, window, spy3.
6384 * We then inject an event and verify that the foreground "window" receives it first, followed by
6385 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6386 * window.
6387 */
6388TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6389 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006390 auto spy1 = createSpy();
6391 auto spy2 = createSpy();
6392 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006393 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6394 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6395 const size_t numChannels = channels.size();
6396
Michael Wright8e9a8562022-02-09 13:44:29 +00006397 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006398 if (!epollFd.ok()) {
6399 FAIL() << "Failed to create epoll fd";
6400 }
6401
6402 for (size_t i = 0; i < numChannels; i++) {
6403 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6404 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6405 FAIL() << "Failed to add fd to epoll";
6406 }
6407 }
6408
6409 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6410 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6411 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6412
6413 std::vector<size_t> eventOrder;
6414 std::vector<struct epoll_event> events(numChannels);
6415 for (;;) {
6416 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6417 (100ms).count());
6418 if (nFds < 0) {
6419 FAIL() << "Failed to call epoll_wait";
6420 }
6421 if (nFds == 0) {
6422 break; // epoll_wait timed out
6423 }
6424 for (int i = 0; i < nFds; i++) {
6425 ASSERT_EQ(EPOLLIN, events[i].events);
6426 eventOrder.push_back(events[i].data.u64);
6427 channels[i]->consumeMotionDown();
6428 }
6429 }
6430
6431 // Verify the order in which the events were received.
6432 EXPECT_EQ(3u, eventOrder.size());
6433 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6434 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6435 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6436}
6437
6438/**
6439 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6440 */
6441TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6442 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006443 auto spy = createSpy();
6444 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006445 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6446
6447 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6448 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6449 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6450 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6451 spy->assertNoEvents();
6452}
6453
6454/**
6455 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6456 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6457 * to the window.
6458 */
6459TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6460 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006461 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006462 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6463 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6464
6465 // Inject an event outside the spy window's touchable region.
6466 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6467 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6468 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6469 window->consumeMotionDown();
6470 spy->assertNoEvents();
6471 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6472 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6473 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6474 window->consumeMotionUp();
6475 spy->assertNoEvents();
6476
6477 // Inject an event inside the spy window's touchable region.
6478 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6479 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6480 {5, 10}))
6481 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6482 window->consumeMotionDown();
6483 spy->consumeMotionDown();
6484}
6485
6486/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006487 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006488 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006489 */
6490TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6491 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006492 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006493 auto spy = createSpy();
6494 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006495 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006496 spy->setFrame(Rect{0, 0, 20, 20});
6497 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6498
6499 // Inject an event outside the spy window's frame and touchable region.
6500 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006501 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6502 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006503 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6504 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006505 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006506}
6507
6508/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006509 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6510 * any other windows - including other spy windows - will also be cancelled.
6511 */
6512TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6513 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006514 auto spy1 = createSpy();
6515 auto spy2 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006516 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6517
6518 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6519 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6520 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6521 window->consumeMotionDown();
6522 spy1->consumeMotionDown();
6523 spy2->consumeMotionDown();
6524
6525 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006526 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006527 spy2->assertNoEvents();
6528 spy1->consumeMotionCancel();
6529 window->consumeMotionCancel();
6530
6531 // The rest of the gesture should only be sent to the second spy window.
6532 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6533 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6534 ADISPLAY_ID_DEFAULT))
6535 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6536 spy2->consumeMotionMove();
6537 spy1->assertNoEvents();
6538 window->assertNoEvents();
6539}
6540
6541/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006542 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
6543 * in the middle of the gesture.
6544 */
6545TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
6546 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006547 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006548 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6549
6550 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6551 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6552 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6553 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6554 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6555
6556 window->releaseChannel();
6557
6558 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6559
6560 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6561 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6562 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6563 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6564}
6565
6566/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006567 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
6568 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006569 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006570TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006571 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006572 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006573
6574 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6575
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006576 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006577 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6578 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6579 {100, 200}))
6580 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006581 spy->consumeMotionDown();
6582 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006583
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006584 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006585 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006586 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006587
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006588 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006589 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006590 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006591 .displayId(ADISPLAY_ID_DEFAULT)
6592 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6593 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6594 .x(100)
6595 .y(200))
6596 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6597 .build();
6598 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6599 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6600 InputEventInjectionSync::WAIT_FOR_RESULT))
6601 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6602
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006603 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6604
6605 // Third finger goes down outside all windows, so injection should fail.
6606 const MotionEvent thirdFingerDownEvent =
6607 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6608 (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6609 AINPUT_SOURCE_TOUCHSCREEN)
6610 .displayId(ADISPLAY_ID_DEFAULT)
6611 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6612 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6613 .x(100)
6614 .y(200))
6615 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6616 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
6617 .build();
6618 ASSERT_EQ(InputEventInjectionResult::FAILED,
6619 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
6620 InputEventInjectionSync::WAIT_FOR_RESULT))
6621 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6622
6623 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006624 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006625}
6626
6627/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006628 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6629 * pointers that are down within its bounds.
6630 */
6631TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6632 auto windowLeft = createForeground();
6633 windowLeft->setFrame({0, 0, 100, 200});
6634 auto windowRight = createForeground();
6635 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006636 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006637 spy->setFrame({0, 0, 200, 200});
6638 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6639
6640 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6641 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6642 {50, 50}))
6643 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6644 windowLeft->consumeMotionDown();
6645 spy->consumeMotionDown();
6646
6647 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006648 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006649 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6650 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6651 .pointer(
6652 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6653 .build();
6654 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6655 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6656 InputEventInjectionSync::WAIT_FOR_RESULT))
6657 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6658 windowRight->consumeMotionDown();
6659 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6660}
6661
6662/**
6663 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6664 * the spy should receive the second pointer with ACTION_DOWN.
6665 */
6666TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6667 auto window = createForeground();
6668 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006669 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006670 spyRight->setFrame({100, 0, 200, 200});
6671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6672
6673 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6674 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6675 {50, 50}))
6676 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6677 window->consumeMotionDown();
6678 spyRight->assertNoEvents();
6679
6680 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006681 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006682 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6683 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6684 .pointer(
6685 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6686 .build();
6687 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6688 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6689 InputEventInjectionSync::WAIT_FOR_RESULT))
6690 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6691 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6692 spyRight->consumeMotionDown();
6693}
6694
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006695/**
6696 * The spy window should not be able to affect whether or not touches are split. Only the foreground
6697 * windows should be allowed to control split touch.
6698 */
6699TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006700 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006701 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006702 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006703 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006704
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006705 auto window = createForeground();
6706 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006707
6708 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6709
6710 // First finger down, no window touched.
6711 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6712 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6713 {100, 200}))
6714 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6715 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6716 window->assertNoEvents();
6717
6718 // Second finger down on window, the window should receive touch down.
6719 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006720 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006721 .displayId(ADISPLAY_ID_DEFAULT)
6722 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6723 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6724 .x(100)
6725 .y(200))
6726 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6727 .build();
6728 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6729 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6730 InputEventInjectionSync::WAIT_FOR_RESULT))
6731 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6732
6733 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6734 spy->consumeMotionPointerDown(1 /* pointerIndex */);
6735}
6736
6737/**
6738 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
6739 * do not receive key events.
6740 */
6741TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006742 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006743 spy->setFocusable(false);
6744
6745 auto window = createForeground();
6746 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6747 setFocusedWindow(window);
6748 window->consumeFocusEvent(true);
6749
6750 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6751 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6752 window->consumeKeyDown(ADISPLAY_ID_NONE);
6753
6754 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6755 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6756 window->consumeKeyUp(ADISPLAY_ID_NONE);
6757
6758 spy->assertNoEvents();
6759}
6760
Prabir Pradhand65552b2021-10-07 11:23:50 -07006761class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6762public:
6763 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6764 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6765 std::make_shared<FakeApplicationHandle>();
6766 sp<FakeWindowHandle> overlay =
6767 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6768 ADISPLAY_ID_DEFAULT);
6769 overlay->setFocusable(false);
6770 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006771 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006772 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006773 overlay->setTrustedOverlay(true);
6774
6775 std::shared_ptr<FakeApplicationHandle> application =
6776 std::make_shared<FakeApplicationHandle>();
6777 sp<FakeWindowHandle> window =
6778 new FakeWindowHandle(application, mDispatcher, "Application window",
6779 ADISPLAY_ID_DEFAULT);
6780 window->setFocusable(true);
6781 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006782
6783 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6784 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6785 setFocusedWindow(window);
6786 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6787 return {std::move(overlay), std::move(window)};
6788 }
6789
6790 void sendFingerEvent(int32_t action) {
6791 NotifyMotionArgs motionArgs =
6792 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6793 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6794 mDispatcher->notifyMotion(&motionArgs);
6795 }
6796
6797 void sendStylusEvent(int32_t action) {
6798 NotifyMotionArgs motionArgs =
6799 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6800 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6801 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6802 mDispatcher->notifyMotion(&motionArgs);
6803 }
6804};
6805
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006806using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
6807
6808TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
6809 ScopedSilentDeath _silentDeath;
6810
Prabir Pradhand65552b2021-10-07 11:23:50 -07006811 auto [overlay, window] = setupStylusOverlayScenario();
6812 overlay->setTrustedOverlay(false);
6813 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6814 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6815 ".* not a trusted overlay");
6816}
6817
6818TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6819 auto [overlay, window] = setupStylusOverlayScenario();
6820 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6821
6822 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6823 overlay->consumeMotionDown();
6824 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6825 overlay->consumeMotionUp();
6826
6827 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6828 window->consumeMotionDown();
6829 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6830 window->consumeMotionUp();
6831
6832 overlay->assertNoEvents();
6833 window->assertNoEvents();
6834}
6835
6836TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6837 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006838 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006839 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6840
6841 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6842 overlay->consumeMotionDown();
6843 window->consumeMotionDown();
6844 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6845 overlay->consumeMotionUp();
6846 window->consumeMotionUp();
6847
6848 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6849 window->consumeMotionDown();
6850 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6851 window->consumeMotionUp();
6852
6853 overlay->assertNoEvents();
6854 window->assertNoEvents();
6855}
6856
Garfield Tane84e6f92019-08-29 17:28:41 -07006857} // namespace android::inputdispatcher