blob: 7ac9ed98b19077b0f7d9e4571a08963e160c8df0 [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
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800292 /**
293 * Set policy timeout. A value of zero means next key will not be intercepted.
294 */
295 void setInterceptKeyTimeout(std::chrono::milliseconds timeout) {
296 mInterceptKeyTimeout = timeout;
297 }
298
Michael Wrightd02c5b62014-02-10 15:10:22 -0800299private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700300 std::mutex mLock;
301 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
302 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
303 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
304 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800305
Prabir Pradhan99987712020-11-10 18:43:05 -0800306 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000307
308 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800309
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700310 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700311 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800312 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
313 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700314 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800315 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
316 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700317
arthurhungf452d0b2021-01-06 00:19:52 +0800318 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800319 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800320
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800321 std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
322
Prabir Pradhanedd96402022-02-15 01:46:16 -0800323 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
324 // for a specific container to become non-empty. When the container is non-empty, return the
325 // first entry from the container and erase it.
326 template <class T>
327 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
328 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
329 // If there is an ANR, Dispatcher won't be idle because there are still events
330 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
331 // before checking if ANR was called.
332 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
333 // to provide it some time to act. 100ms seems reasonable.
334 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
335 const std::chrono::time_point start = std::chrono::steady_clock::now();
336 std::optional<T> token =
337 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
338 if (!token.has_value()) {
339 ADD_FAILURE() << "Did not receive the ANR callback";
340 return {};
341 }
342
343 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
344 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
345 // the dispatcher started counting before this function was called
346 if (std::chrono::abs(timeout - waited) > 100ms) {
347 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
348 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
349 << "ms, but waited "
350 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
351 << "ms instead";
352 }
353 return *token;
354 }
355
356 template <class T>
357 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
358 std::queue<T>& storage,
359 std::unique_lock<std::mutex>& lock,
360 std::condition_variable& condition)
361 REQUIRES(mLock) {
362 condition.wait_for(lock, timeout,
363 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
364 if (storage.empty()) {
365 ADD_FAILURE() << "Did not receive the expected callback";
366 return std::nullopt;
367 }
368 T item = storage.front();
369 storage.pop();
370 return std::make_optional(item);
371 }
372
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600373 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700374 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800375 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800376 }
377
Prabir Pradhanedd96402022-02-15 01:46:16 -0800378 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
379 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700380 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800381 ASSERT_TRUE(pid.has_value());
382 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700383 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500384 }
385
Prabir Pradhanedd96402022-02-15 01:46:16 -0800386 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
387 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500388 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800389 ASSERT_TRUE(pid.has_value());
390 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500391 mNotifyAnr.notify_all();
392 }
393
394 void notifyNoFocusedWindowAnr(
395 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
396 std::scoped_lock lock(mLock);
397 mAnrApplications.push(applicationHandle);
398 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800399 }
400
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800401 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
402 std::scoped_lock lock(mLock);
403 mBrokenInputChannels.push(connectionToken);
404 mNotifyInputChannelBroken.notify_all();
405 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800406
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600407 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700408
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600409 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700410 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
411 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
412 const std::vector<float>& values) override {}
413
414 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
415 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000416
Chris Yefb552902021-02-03 17:18:37 -0800417 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
418
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600419 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800420 *outConfig = mConfig;
421 }
422
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600423 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700424 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800425 switch (inputEvent->getType()) {
426 case AINPUT_EVENT_TYPE_KEY: {
427 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800428 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800429 break;
430 }
431
432 case AINPUT_EVENT_TYPE_MOTION: {
433 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800434 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800435 break;
436 }
437 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800438 return true;
439 }
440
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800441 void interceptKeyBeforeQueueing(const KeyEvent* inputEvent, uint32_t&) override {
442 if (inputEvent->getAction() == AKEY_EVENT_ACTION_UP) {
443 // Clear intercept state when we handled the event.
444 mInterceptKeyTimeout = 0ms;
445 }
446 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800447
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600448 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800449
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600450 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800451 nsecs_t delay = std::chrono::nanoseconds(mInterceptKeyTimeout).count();
452 // Clear intercept state so we could dispatch the event in next wake.
453 mInterceptKeyTimeout = 0ms;
454 return delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455 }
456
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600457 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458 return false;
459 }
460
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600461 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
462 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700463 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800464 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
465 * essentially a passthrough for notifySwitch.
466 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800467 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800468 }
469
Sean Stoutb4e0a592021-02-23 07:34:53 -0800470 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800471
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800472 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
473 return pid == INJECTOR_PID && uid == INJECTOR_UID;
474 }
Jackal Guof9696682018-10-05 12:23:23 +0800475
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600476 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700477 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700478 mOnPointerDownToken = newToken;
479 }
480
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000481 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800482 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000483 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800484 mPointerCaptureChangedCondition.notify_all();
485 }
486
arthurhungf452d0b2021-01-06 00:19:52 +0800487 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
488 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800489 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800490 mDropTargetWindowToken = token;
491 }
492
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700493 void assertFilterInputEventWasCalledInternal(
494 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700495 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800496 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700497 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800498 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500};
501
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502// --- InputDispatcherTest ---
503
504class InputDispatcherTest : public testing::Test {
505protected:
506 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700507 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800508
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000509 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800510 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800511 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800512 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000513 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700514 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515 }
516
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000517 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700518 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700520 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800521 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700522
523 /**
524 * Used for debugging when writing the test
525 */
526 void dumpDispatcherState() {
527 std::string dump;
528 mDispatcher->dump(dump);
529 std::stringstream ss(dump);
530 std::string to;
531
532 while (std::getline(ss, to, '\n')) {
533 ALOGE("%s", to.c_str());
534 }
535 }
Vishnu Nair958da932020-08-21 17:12:37 -0700536
chaviw3277faf2021-05-19 16:45:23 -0500537 void setFocusedWindow(const sp<WindowInfoHandle>& window,
538 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700539 FocusRequest request;
540 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000541 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700542 if (focusedWindow) {
543 request.focusedToken = focusedWindow->getToken();
544 }
545 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
546 request.displayId = window->getInfo()->displayId;
547 mDispatcher->setFocusedWindow(request);
548 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800549};
550
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
552 KeyEvent event;
553
554 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800555 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
556 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600557 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
558 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800559 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700560 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800561 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 << "Should reject key events with undefined action.";
563
564 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800565 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
566 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600567 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800568 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700569 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800570 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800571 << "Should reject key events with ACTION_MULTIPLE.";
572}
573
574TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
575 MotionEvent event;
576 PointerProperties pointerProperties[MAX_POINTERS + 1];
577 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800578 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800579 pointerProperties[i].clear();
580 pointerProperties[i].id = i;
581 pointerCoords[i].clear();
582 }
583
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800584 // Some constants commonly used below
585 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
586 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
587 constexpr int32_t metaState = AMETA_NONE;
588 constexpr MotionClassification classification = MotionClassification::NONE;
589
chaviw9eaa22c2020-07-01 16:21:27 -0700590 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800591 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800592 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700593 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
594 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700595 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
596 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700597 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800598 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700599 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800600 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800601 << "Should reject motion events with undefined action.";
602
603 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800604 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800605 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
606 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
607 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
608 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500609 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800610 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700611 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800612 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800613 << "Should reject motion events with pointer down index too large.";
614
Garfield Tanfbe732e2020-01-24 11:26:14 -0800615 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700616 AMOTION_EVENT_ACTION_POINTER_DOWN |
617 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700618 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
619 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700620 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500621 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800622 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700623 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800624 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800625 << "Should reject motion events with pointer down index too small.";
626
627 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800628 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800629 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
630 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
631 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
632 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500633 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800634 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700635 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800636 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800637 << "Should reject motion events with pointer up index too large.";
638
Garfield Tanfbe732e2020-01-24 11:26:14 -0800639 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700640 AMOTION_EVENT_ACTION_POINTER_UP |
641 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700642 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
643 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700644 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500645 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800646 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700647 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800648 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649 << "Should reject motion events with pointer up index too small.";
650
651 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800652 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
653 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700654 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700655 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
656 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700657 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800658 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700659 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800660 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800661 << "Should reject motion events with 0 pointers.";
662
Garfield Tanfbe732e2020-01-24 11:26:14 -0800663 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
664 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700665 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700666 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
667 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700668 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800669 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700670 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800671 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800672 << "Should reject motion events with more than MAX_POINTERS pointers.";
673
674 // Rejects motion events with invalid pointer ids.
675 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800676 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
677 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700678 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700679 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
680 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700681 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800682 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700683 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800684 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800685 << "Should reject motion events with pointer ids less than 0.";
686
687 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800688 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
689 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700690 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700691 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
692 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700693 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800694 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700695 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800696 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
698
699 // Rejects motion events with duplicate pointer ids.
700 pointerProperties[0].id = 1;
701 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800702 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
703 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700704 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700705 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
706 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700707 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800708 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700709 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800710 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800711 << "Should reject motion events with duplicate pointer ids.";
712}
713
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800714/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
715
716TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
717 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800718 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800719 mDispatcher->notifyConfigurationChanged(&args);
720 ASSERT_TRUE(mDispatcher->waitForIdle());
721
722 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
723}
724
725TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800726 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
727 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800728 mDispatcher->notifySwitch(&args);
729
730 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
731 args.policyFlags |= POLICY_FLAG_TRUSTED;
732 mFakePolicy->assertNotifySwitchWasCalled(args);
733}
734
Arthur Hungb92218b2018-08-14 12:00:21 +0800735// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700736static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700737// Default input dispatching timeout if there is no focused application or paused window
738// from which to determine an appropriate dispatching timeout.
739static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
740 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
741 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800742
743class FakeApplicationHandle : public InputApplicationHandle {
744public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700745 FakeApplicationHandle() {
746 mInfo.name = "Fake Application";
747 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500748 mInfo.dispatchingTimeoutMillis =
749 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700750 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800751 virtual ~FakeApplicationHandle() {}
752
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000753 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700754
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500755 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
756 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700757 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800758};
759
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800760class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800761public:
Garfield Tan15601662020-09-22 15:32:38 -0700762 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800763 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700764 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800765 }
766
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800767 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700768 InputEvent* event;
769 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
770 if (!consumeSeq) {
771 return nullptr;
772 }
773 finishEvent(*consumeSeq);
774 return event;
775 }
776
777 /**
778 * Receive an event without acknowledging it.
779 * Return the sequence number that could later be used to send finished signal.
780 */
781 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800782 uint32_t consumeSeq;
783 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800784
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800785 std::chrono::time_point start = std::chrono::steady_clock::now();
786 status_t status = WOULD_BLOCK;
787 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800788 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800789 &event);
790 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
791 if (elapsed > 100ms) {
792 break;
793 }
794 }
795
796 if (status == WOULD_BLOCK) {
797 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700798 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800799 }
800
801 if (status != OK) {
802 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700803 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800804 }
805 if (event == nullptr) {
806 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700807 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800808 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700809 if (outEvent != nullptr) {
810 *outEvent = event;
811 }
812 return consumeSeq;
813 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800814
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700815 /**
816 * To be used together with "receiveEvent" to complete the consumption of an event.
817 */
818 void finishEvent(uint32_t consumeSeq) {
819 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
820 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800821 }
822
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000823 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
824 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
825 ASSERT_EQ(OK, status);
826 }
827
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000828 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
829 std::optional<int32_t> expectedDisplayId,
830 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800831 InputEvent* event = consume();
832
833 ASSERT_NE(nullptr, event) << mName.c_str()
834 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800835 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700836 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800837 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800838
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000839 if (expectedDisplayId.has_value()) {
840 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
841 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800842
Tiger Huang8664f8c2018-10-11 19:14:35 +0800843 switch (expectedEventType) {
844 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800845 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
846 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000847 if (expectedFlags.has_value()) {
848 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
849 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800850 break;
851 }
852 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800853 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000854 assertMotionAction(expectedAction, motionEvent.getAction());
855
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000856 if (expectedFlags.has_value()) {
857 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
858 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800859 break;
860 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100861 case AINPUT_EVENT_TYPE_FOCUS: {
862 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
863 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800864 case AINPUT_EVENT_TYPE_CAPTURE: {
865 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
866 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000867 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
868 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
869 }
arthurhungb89ccb02020-12-30 16:19:01 +0800870 case AINPUT_EVENT_TYPE_DRAG: {
871 FAIL() << "Use 'consumeDragEvent' for DRAG events";
872 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800873 default: {
874 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
875 }
876 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800877 }
878
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100879 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
880 InputEvent* event = consume();
881 ASSERT_NE(nullptr, event) << mName.c_str()
882 << ": consumer should have returned non-NULL event.";
883 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
884 << "Got " << inputEventTypeToString(event->getType())
885 << " event instead of FOCUS event";
886
887 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
888 << mName.c_str() << ": event displayId should always be NONE.";
889
890 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
891 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100892 }
893
Prabir Pradhan99987712020-11-10 18:43:05 -0800894 void consumeCaptureEvent(bool hasCapture) {
895 const InputEvent* event = consume();
896 ASSERT_NE(nullptr, event) << mName.c_str()
897 << ": consumer should have returned non-NULL event.";
898 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
899 << "Got " << inputEventTypeToString(event->getType())
900 << " event instead of CAPTURE event";
901
902 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
903 << mName.c_str() << ": event displayId should always be NONE.";
904
905 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
906 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
907 }
908
arthurhungb89ccb02020-12-30 16:19:01 +0800909 void consumeDragEvent(bool isExiting, float x, float y) {
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_DRAG, event->getType())
914 << "Got " << inputEventTypeToString(event->getType())
915 << " event instead of DRAG event";
916
917 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
918 << mName.c_str() << ": event displayId should always be NONE.";
919
920 const auto& dragEvent = static_cast<const DragEvent&>(*event);
921 EXPECT_EQ(isExiting, dragEvent.isExiting());
922 EXPECT_EQ(x, dragEvent.getX());
923 EXPECT_EQ(y, dragEvent.getY());
924 }
925
Antonio Kantekf16f2832021-09-28 04:39:20 +0000926 void consumeTouchModeEvent(bool inTouchMode) {
927 const InputEvent* event = consume();
928 ASSERT_NE(nullptr, event) << mName.c_str()
929 << ": consumer should have returned non-NULL event.";
930 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
931 << "Got " << inputEventTypeToString(event->getType())
932 << " event instead of TOUCH_MODE event";
933
934 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
935 << mName.c_str() << ": event displayId should always be NONE.";
936 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
937 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
938 }
939
chaviwd1c23182019-12-20 18:44:56 -0800940 void assertNoEvents() {
941 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700942 if (event == nullptr) {
943 return;
944 }
945 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
946 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
947 ADD_FAILURE() << "Received key event "
948 << KeyEvent::actionToString(keyEvent.getAction());
949 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
950 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
951 ADD_FAILURE() << "Received motion event "
952 << MotionEvent::actionToString(motionEvent.getAction());
953 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
954 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
955 ADD_FAILURE() << "Received focus event, hasFocus = "
956 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800957 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
958 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
959 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
960 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000961 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
962 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
963 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
964 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700965 }
966 FAIL() << mName.c_str()
967 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800968 }
969
970 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
971
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800972 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
973
chaviwd1c23182019-12-20 18:44:56 -0800974protected:
975 std::unique_ptr<InputConsumer> mConsumer;
976 PreallocatedInputEventFactory mEventFactory;
977
978 std::string mName;
979};
980
chaviw3277faf2021-05-19 16:45:23 -0500981class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800982public:
983 static const int32_t WIDTH = 600;
984 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800985
Chris Yea209fde2020-07-22 13:54:51 -0700986 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700987 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500988 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800989 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500990 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700991 base::Result<std::unique_ptr<InputChannel>> channel =
992 dispatcher->createInputChannel(name);
993 token = (*channel)->getConnectionToken();
994 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800995 }
996
997 inputApplicationHandle->updateInfo();
998 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
999
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001000 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001001 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001002 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001003 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001004 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001005 mInfo.frameLeft = 0;
1006 mInfo.frameTop = 0;
1007 mInfo.frameRight = WIDTH;
1008 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001009 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001010 mInfo.globalScaleFactor = 1.0;
1011 mInfo.touchableRegion.clear();
1012 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
chaviwd1c23182019-12-20 18:44:56 -08001013 mInfo.ownerPid = INJECTOR_PID;
1014 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -08001015 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001016 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001017 }
1018
Arthur Hungabbb9d82021-09-01 14:52:30 +00001019 sp<FakeWindowHandle> clone(
1020 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001021 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001022 sp<FakeWindowHandle> handle =
1023 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1024 displayId, mInfo.token);
1025 return handle;
1026 }
1027
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001028 void setTouchable(bool touchable) {
1029 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1030 }
chaviwd1c23182019-12-20 18:44:56 -08001031
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001032 void setFocusable(bool focusable) {
1033 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1034 }
1035
1036 void setVisible(bool visible) {
1037 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1038 }
Vishnu Nair958da932020-08-21 17:12:37 -07001039
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001040 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001041 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001042 }
1043
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001044 void setPaused(bool paused) {
1045 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1046 }
1047
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001048 void setPreventSplitting(bool preventSplitting) {
1049 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001050 }
1051
1052 void setSlippery(bool slippery) {
1053 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1054 }
1055
1056 void setWatchOutsideTouch(bool watchOutside) {
1057 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1058 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001059
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001060 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1061
1062 void setInterceptsStylus(bool interceptsStylus) {
1063 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1064 }
1065
1066 void setDropInput(bool dropInput) {
1067 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1068 }
1069
1070 void setDropInputIfObscured(bool dropInputIfObscured) {
1071 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1072 }
1073
1074 void setNoInputChannel(bool noInputChannel) {
1075 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1076 }
1077
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001078 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1079
chaviw3277faf2021-05-19 16:45:23 -05001080 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001081
Bernardo Rufino7393d172021-02-26 13:56:11 +00001082 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1083
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001084 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001085 mInfo.frameLeft = frame.left;
1086 mInfo.frameTop = frame.top;
1087 mInfo.frameRight = frame.right;
1088 mInfo.frameBottom = frame.bottom;
1089 mInfo.touchableRegion.clear();
1090 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001091
1092 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1093 ui::Transform translate;
1094 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1095 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001096 }
1097
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001098 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1099
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001100 void setIsWallpaper(bool isWallpaper) {
1101 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1102 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001103
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001104 void setDupTouchToWallpaper(bool hasWallpaper) {
1105 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1106 }
chaviwd1c23182019-12-20 18:44:56 -08001107
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001108 void setTrustedOverlay(bool trustedOverlay) {
1109 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1110 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001111
chaviw9eaa22c2020-07-01 16:21:27 -07001112 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1113 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1114 }
1115
1116 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001117
yunho.shinf4a80b82020-11-16 21:13:57 +09001118 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1119
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001120 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1121 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1122 expectedFlags);
1123 }
1124
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001125 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1126 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1127 }
1128
Svet Ganov5d3bc372020-01-26 23:11:07 -08001129 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001130 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001131 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1132 expectedFlags);
1133 }
1134
1135 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001136 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001137 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1138 expectedFlags);
1139 }
1140
1141 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001142 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001143 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1144 }
1145
1146 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1147 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001148 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1149 expectedFlags);
1150 }
1151
Svet Ganov5d3bc372020-01-26 23:11:07 -08001152 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001153 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1154 int32_t expectedFlags = 0) {
1155 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1156 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001157 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1158 }
1159
1160 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001161 int32_t expectedFlags = 0) {
1162 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1163 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001164 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1165 }
1166
1167 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001168 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001169 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1170 expectedFlags);
1171 }
1172
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001173 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1174 int32_t expectedFlags = 0) {
1175 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1176 expectedFlags);
1177 }
1178
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001179 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1180 int32_t expectedFlags = 0) {
1181 InputEvent* event = consume();
1182 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1183 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1184 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1185 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1186 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1187 }
1188
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001189 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1190 ASSERT_NE(mInputReceiver, nullptr)
1191 << "Cannot consume events from a window with no receiver";
1192 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1193 }
1194
Prabir Pradhan99987712020-11-10 18:43:05 -08001195 void consumeCaptureEvent(bool hasCapture) {
1196 ASSERT_NE(mInputReceiver, nullptr)
1197 << "Cannot consume events from a window with no receiver";
1198 mInputReceiver->consumeCaptureEvent(hasCapture);
1199 }
1200
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001201 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1202 std::optional<int32_t> expectedDisplayId,
1203 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001204 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1205 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1206 expectedFlags);
1207 }
1208
arthurhungb89ccb02020-12-30 16:19:01 +08001209 void consumeDragEvent(bool isExiting, float x, float y) {
1210 mInputReceiver->consumeDragEvent(isExiting, x, y);
1211 }
1212
Antonio Kantekf16f2832021-09-28 04:39:20 +00001213 void consumeTouchModeEvent(bool inTouchMode) {
1214 ASSERT_NE(mInputReceiver, nullptr)
1215 << "Cannot consume events from a window with no receiver";
1216 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1217 }
1218
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001219 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001220 if (mInputReceiver == nullptr) {
1221 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1222 return std::nullopt;
1223 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001224 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001225 }
1226
1227 void finishEvent(uint32_t sequenceNum) {
1228 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1229 mInputReceiver->finishEvent(sequenceNum);
1230 }
1231
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001232 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1233 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1234 mInputReceiver->sendTimeline(inputEventId, timeline);
1235 }
1236
chaviwaf87b3e2019-10-01 16:59:28 -07001237 InputEvent* consume() {
1238 if (mInputReceiver == nullptr) {
1239 return nullptr;
1240 }
1241 return mInputReceiver->consume();
1242 }
1243
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001244 MotionEvent* consumeMotion() {
1245 InputEvent* event = consume();
1246 if (event == nullptr) {
1247 ADD_FAILURE() << "Consume failed : no event";
1248 return nullptr;
1249 }
1250 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1251 ADD_FAILURE() << "Instead of motion event, got "
1252 << inputEventTypeToString(event->getType());
1253 return nullptr;
1254 }
1255 return static_cast<MotionEvent*>(event);
1256 }
1257
Arthur Hungb92218b2018-08-14 12:00:21 +08001258 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001259 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001260 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001261 return; // Can't receive events if the window does not have input channel
1262 }
1263 ASSERT_NE(nullptr, mInputReceiver)
1264 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001265 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001266 }
1267
chaviwaf87b3e2019-10-01 16:59:28 -07001268 sp<IBinder> getToken() { return mInfo.token; }
1269
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001270 const std::string& getName() { return mName; }
1271
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001272 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1273 mInfo.ownerPid = ownerPid;
1274 mInfo.ownerUid = ownerUid;
1275 }
1276
Prabir Pradhanedd96402022-02-15 01:46:16 -08001277 int32_t getPid() const { return mInfo.ownerPid; }
1278
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001279 void destroyReceiver() { mInputReceiver = nullptr; }
1280
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001281 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1282
chaviwd1c23182019-12-20 18:44:56 -08001283private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001284 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001285 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001286 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001287};
1288
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001289std::atomic<int32_t> FakeWindowHandle::sId{1};
1290
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001291static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001292 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001293 int32_t displayId = ADISPLAY_ID_NONE,
1294 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001295 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1296 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001297 KeyEvent event;
1298 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1299
1300 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001301 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001302 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1303 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001304
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001305 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1306 if (!allowKeyRepeat) {
1307 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1308 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001309 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001310 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001311 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001312}
1313
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001314static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001315 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001316 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1317}
1318
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001319// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1320// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1321// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001322static InputEventInjectionResult injectKeyDownNoRepeat(
1323 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001324 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1325 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1326 /* allowKeyRepeat */ false);
1327}
1328
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001329static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001330 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001331 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1332}
1333
Garfield Tandf26e862020-07-01 20:18:19 -07001334class PointerBuilder {
1335public:
1336 PointerBuilder(int32_t id, int32_t toolType) {
1337 mProperties.clear();
1338 mProperties.id = id;
1339 mProperties.toolType = toolType;
1340 mCoords.clear();
1341 }
1342
1343 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1344
1345 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1346
1347 PointerBuilder& axis(int32_t axis, float value) {
1348 mCoords.setAxisValue(axis, value);
1349 return *this;
1350 }
1351
1352 PointerProperties buildProperties() const { return mProperties; }
1353
1354 PointerCoords buildCoords() const { return mCoords; }
1355
1356private:
1357 PointerProperties mProperties;
1358 PointerCoords mCoords;
1359};
1360
1361class MotionEventBuilder {
1362public:
1363 MotionEventBuilder(int32_t action, int32_t source) {
1364 mAction = action;
1365 mSource = source;
1366 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1367 }
1368
1369 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1370 mEventTime = eventTime;
1371 return *this;
1372 }
1373
1374 MotionEventBuilder& displayId(int32_t displayId) {
1375 mDisplayId = displayId;
1376 return *this;
1377 }
1378
1379 MotionEventBuilder& actionButton(int32_t actionButton) {
1380 mActionButton = actionButton;
1381 return *this;
1382 }
1383
arthurhung6d4bed92021-03-17 11:59:33 +08001384 MotionEventBuilder& buttonState(int32_t buttonState) {
1385 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001386 return *this;
1387 }
1388
1389 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1390 mRawXCursorPosition = rawXCursorPosition;
1391 return *this;
1392 }
1393
1394 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1395 mRawYCursorPosition = rawYCursorPosition;
1396 return *this;
1397 }
1398
1399 MotionEventBuilder& pointer(PointerBuilder pointer) {
1400 mPointers.push_back(pointer);
1401 return *this;
1402 }
1403
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001404 MotionEventBuilder& addFlag(uint32_t flags) {
1405 mFlags |= flags;
1406 return *this;
1407 }
1408
Garfield Tandf26e862020-07-01 20:18:19 -07001409 MotionEvent build() {
1410 std::vector<PointerProperties> pointerProperties;
1411 std::vector<PointerCoords> pointerCoords;
1412 for (const PointerBuilder& pointer : mPointers) {
1413 pointerProperties.push_back(pointer.buildProperties());
1414 pointerCoords.push_back(pointer.buildCoords());
1415 }
1416
1417 // Set mouse cursor position for the most common cases to avoid boilerplate.
1418 if (mSource == AINPUT_SOURCE_MOUSE &&
1419 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1420 mPointers.size() == 1) {
1421 mRawXCursorPosition = pointerCoords[0].getX();
1422 mRawYCursorPosition = pointerCoords[0].getY();
1423 }
1424
1425 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001426 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001427 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001428 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001429 mButtonState, MotionClassification::NONE, identityTransform,
1430 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001431 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1432 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001433
1434 return event;
1435 }
1436
1437private:
1438 int32_t mAction;
1439 int32_t mSource;
1440 nsecs_t mEventTime;
1441 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1442 int32_t mActionButton{0};
1443 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001444 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001445 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1446 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1447
1448 std::vector<PointerBuilder> mPointers;
1449};
1450
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001451static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001452 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001453 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001454 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001455 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1456 injectionTimeout,
1457 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1458}
1459
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001460static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001461 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001462 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001463 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001464 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1465 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001466 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001467 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001468 MotionEvent event = MotionEventBuilder(action, source)
1469 .displayId(displayId)
1470 .eventTime(eventTime)
1471 .rawXCursorPosition(cursorPosition.x)
1472 .rawYCursorPosition(cursorPosition.y)
1473 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1474 .x(position.x)
1475 .y(position.y))
1476 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001477
1478 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001479 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001480}
1481
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001482static InputEventInjectionResult injectMotionDown(
1483 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1484 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001485 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001486}
1487
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001488static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001489 int32_t source, int32_t displayId,
1490 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001491 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001492}
1493
Jackal Guof9696682018-10-05 12:23:23 +08001494static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1495 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1496 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001497 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1498 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1499 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001500
1501 return args;
1502}
1503
chaviwd1c23182019-12-20 18:44:56 -08001504static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1505 const std::vector<PointF>& points) {
1506 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001507 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1508 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1509 }
1510
chaviwd1c23182019-12-20 18:44:56 -08001511 PointerProperties pointerProperties[pointerCount];
1512 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001513
chaviwd1c23182019-12-20 18:44:56 -08001514 for (size_t i = 0; i < pointerCount; i++) {
1515 pointerProperties[i].clear();
1516 pointerProperties[i].id = i;
1517 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001518
chaviwd1c23182019-12-20 18:44:56 -08001519 pointerCoords[i].clear();
1520 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1521 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1522 }
Jackal Guof9696682018-10-05 12:23:23 +08001523
1524 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1525 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001526 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001527 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1528 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001529 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1530 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001531 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1532 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001533
1534 return args;
1535}
1536
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001537static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1538 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1539}
1540
chaviwd1c23182019-12-20 18:44:56 -08001541static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1542 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1543}
1544
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001545static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1546 const PointerCaptureRequest& request) {
1547 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001548}
1549
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001550/**
1551 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1552 * broken channel.
1553 */
1554TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1555 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1556 sp<FakeWindowHandle> window =
1557 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1558 ADISPLAY_ID_DEFAULT);
1559
1560 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1561
1562 // Window closes its channel, but the window remains.
1563 window->destroyReceiver();
1564 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1565}
1566
Arthur Hungb92218b2018-08-14 12:00:21 +08001567TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001568 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001569 sp<FakeWindowHandle> window =
1570 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001571
Arthur Hung72d8dc32020-03-28 00:48:39 +00001572 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001573 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1574 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1575 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001576
1577 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001578 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001579}
1580
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001581TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1582 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1583 sp<FakeWindowHandle> window =
1584 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1585
1586 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1587 // Inject a MotionEvent to an unknown display.
1588 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1589 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1590 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1591
1592 // Window should receive motion event.
1593 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1594}
1595
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001596/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001597 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001598 * This test serves as a sanity check for the next test, where setInputWindows is
1599 * called twice.
1600 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001601TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001602 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001603 sp<FakeWindowHandle> window =
1604 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1605 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001606
1607 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001608 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001609 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1610 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001611 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001612
1613 // Window should receive motion event.
1614 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1615}
1616
1617/**
1618 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001619 */
1620TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001621 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001622 sp<FakeWindowHandle> window =
1623 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1624 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001625
1626 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1627 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001628 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001629 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1630 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001631 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001632
1633 // Window should receive motion event.
1634 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1635}
1636
Arthur Hungb92218b2018-08-14 12:00:21 +08001637// The foreground window should receive the first touch down event.
1638TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001639 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001640 sp<FakeWindowHandle> windowTop =
1641 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1642 sp<FakeWindowHandle> windowSecond =
1643 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001644
Arthur Hung72d8dc32020-03-28 00:48:39 +00001645 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001646 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1647 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1648 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001649
1650 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001651 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001652 windowSecond->assertNoEvents();
1653}
1654
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001655/**
1656 * Two windows: A top window, and a wallpaper behind the window.
1657 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1658 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001659 * 1. foregroundWindow <-- dup touch to wallpaper
1660 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001661 */
1662TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1663 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1664 sp<FakeWindowHandle> foregroundWindow =
1665 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001666 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001667 sp<FakeWindowHandle> wallpaperWindow =
1668 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001669 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001670 constexpr int expectedWallpaperFlags =
1671 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1672
1673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1674 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1675 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1676 {100, 200}))
1677 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1678
1679 // Both foreground window and its wallpaper should receive the touch down
1680 foregroundWindow->consumeMotionDown();
1681 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1682
1683 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1684 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1685 ADISPLAY_ID_DEFAULT, {110, 200}))
1686 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1687
1688 foregroundWindow->consumeMotionMove();
1689 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1690
1691 // Now the foreground window goes away, but the wallpaper stays
1692 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1693 foregroundWindow->consumeMotionCancel();
1694 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1695 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1696}
1697
1698/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001699 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1700 * with the following differences:
1701 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1702 * clean up the connection.
1703 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1704 * Ensure that there's no crash in the dispatcher.
1705 */
1706TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1707 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1708 sp<FakeWindowHandle> foregroundWindow =
1709 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001710 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001711 sp<FakeWindowHandle> wallpaperWindow =
1712 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001713 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001714 constexpr int expectedWallpaperFlags =
1715 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1716
1717 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1718 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1719 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1720 {100, 200}))
1721 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1722
1723 // Both foreground window and its wallpaper should receive the touch down
1724 foregroundWindow->consumeMotionDown();
1725 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1726
1727 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1728 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1729 ADISPLAY_ID_DEFAULT, {110, 200}))
1730 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1731
1732 foregroundWindow->consumeMotionMove();
1733 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1734
1735 // Wallpaper closes its channel, but the window remains.
1736 wallpaperWindow->destroyReceiver();
1737 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1738
1739 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1740 // is no longer valid.
1741 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1742 foregroundWindow->consumeMotionCancel();
1743}
1744
1745/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001746 * A single window that receives touch (on top), and a wallpaper window underneath it.
1747 * The top window gets a multitouch gesture.
1748 * Ensure that wallpaper gets the same gesture.
1749 */
1750TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1751 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1752 sp<FakeWindowHandle> window =
1753 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001754 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001755
1756 sp<FakeWindowHandle> wallpaperWindow =
1757 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001758 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001759 constexpr int expectedWallpaperFlags =
1760 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1761
1762 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1763
1764 // Touch down on top window
1765 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1766 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1767 {100, 100}))
1768 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1769
1770 // Both top window and its wallpaper should receive the touch down
1771 window->consumeMotionDown();
1772 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1773
1774 // Second finger down on the top window
1775 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001776 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001777 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1778 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1779 .x(100)
1780 .y(100))
1781 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1782 .x(150)
1783 .y(150))
1784 .build();
1785 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1786 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1787 InputEventInjectionSync::WAIT_FOR_RESULT))
1788 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1789
1790 window->consumeMotionPointerDown(1 /* pointerIndex */);
1791 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1792 expectedWallpaperFlags);
1793 window->assertNoEvents();
1794 wallpaperWindow->assertNoEvents();
1795}
1796
1797/**
1798 * Two windows: a window on the left and window on the right.
1799 * A third window, wallpaper, is behind both windows, and spans both top windows.
1800 * The first touch down goes to the left window. A second pointer touches down on the right window.
1801 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1802 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1803 * ACTION_POINTER_DOWN(1).
1804 */
1805TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1806 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1807 sp<FakeWindowHandle> leftWindow =
1808 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1809 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001810 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001811
1812 sp<FakeWindowHandle> rightWindow =
1813 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1814 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001815 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001816
1817 sp<FakeWindowHandle> wallpaperWindow =
1818 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1819 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001820 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001821 constexpr int expectedWallpaperFlags =
1822 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1823
1824 mDispatcher->setInputWindows(
1825 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1826
1827 // Touch down on left window
1828 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1829 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1830 {100, 100}))
1831 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1832
1833 // Both foreground window and its wallpaper should receive the touch down
1834 leftWindow->consumeMotionDown();
1835 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1836
1837 // Second finger down on the right window
1838 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001839 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001840 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1841 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1842 .x(100)
1843 .y(100))
1844 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1845 .x(300)
1846 .y(100))
1847 .build();
1848 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1849 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1850 InputEventInjectionSync::WAIT_FOR_RESULT))
1851 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1852
1853 leftWindow->consumeMotionMove();
1854 // Since the touch is split, right window gets ACTION_DOWN
1855 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1856 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1857 expectedWallpaperFlags);
1858
1859 // Now, leftWindow, which received the first finger, disappears.
1860 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1861 leftWindow->consumeMotionCancel();
1862 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1863 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1864
1865 // The pointer that's still down on the right window moves, and goes to the right window only.
1866 // As far as the dispatcher's concerned though, both pointers are still present.
1867 const MotionEvent secondFingerMoveEvent =
1868 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1869 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1870 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1871 .x(100)
1872 .y(100))
1873 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1874 .x(310)
1875 .y(110))
1876 .build();
1877 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1878 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1879 InputEventInjectionSync::WAIT_FOR_RESULT));
1880 rightWindow->consumeMotionMove();
1881
1882 leftWindow->assertNoEvents();
1883 rightWindow->assertNoEvents();
1884 wallpaperWindow->assertNoEvents();
1885}
1886
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001887/**
1888 * On the display, have a single window, and also an area where there's no window.
1889 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
1890 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
1891 */
1892TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
1893 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1894 sp<FakeWindowHandle> window =
1895 new FakeWindowHandle(application, mDispatcher, "Window", DISPLAY_ID);
1896
1897 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
1898 NotifyMotionArgs args;
1899
1900 // Touch down on the empty space
1901 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
1902
1903 mDispatcher->waitForIdle();
1904 window->assertNoEvents();
1905
1906 // Now touch down on the window with another pointer
1907 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
1908 mDispatcher->waitForIdle();
1909 window->consumeMotionDown();
1910}
1911
1912/**
1913 * Same test as above, but instead of touching the empty space, the first touch goes to
1914 * non-touchable window.
1915 */
1916TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
1917 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1918 sp<FakeWindowHandle> window1 =
1919 new FakeWindowHandle(application, mDispatcher, "Window1", DISPLAY_ID);
1920 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1921 window1->setTouchable(false);
1922 sp<FakeWindowHandle> window2 =
1923 new FakeWindowHandle(application, mDispatcher, "Window2", DISPLAY_ID);
1924 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1925
1926 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1927
1928 NotifyMotionArgs args;
1929 // Touch down on the non-touchable window
1930 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1931
1932 mDispatcher->waitForIdle();
1933 window1->assertNoEvents();
1934 window2->assertNoEvents();
1935
1936 // Now touch down on the window with another pointer
1937 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1938 mDispatcher->waitForIdle();
1939 window2->consumeMotionDown();
1940}
1941
Garfield Tandf26e862020-07-01 20:18:19 -07001942TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001943 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001944 sp<FakeWindowHandle> windowLeft =
1945 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1946 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001947 sp<FakeWindowHandle> windowRight =
1948 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1949 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001950
1951 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1952
1953 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1954
1955 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001956 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001957 injectMotionEvent(mDispatcher,
1958 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1959 AINPUT_SOURCE_MOUSE)
1960 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1961 .x(900)
1962 .y(400))
1963 .build()));
1964 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1965 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1966 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1967 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1968
1969 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001970 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001971 injectMotionEvent(mDispatcher,
1972 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1973 AINPUT_SOURCE_MOUSE)
1974 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1975 .x(300)
1976 .y(400))
1977 .build()));
1978 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1979 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1980 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1981 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1982 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1983 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1984
1985 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001986 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001987 injectMotionEvent(mDispatcher,
1988 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1989 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1990 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1991 .x(300)
1992 .y(400))
1993 .build()));
1994 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1995
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001996 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001997 injectMotionEvent(mDispatcher,
1998 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1999 AINPUT_SOURCE_MOUSE)
2000 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2001 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2002 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2003 .x(300)
2004 .y(400))
2005 .build()));
2006 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2007 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2008
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002009 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002010 injectMotionEvent(mDispatcher,
2011 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2012 AINPUT_SOURCE_MOUSE)
2013 .buttonState(0)
2014 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2015 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2016 .x(300)
2017 .y(400))
2018 .build()));
2019 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2020 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2021
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002022 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002023 injectMotionEvent(mDispatcher,
2024 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2025 .buttonState(0)
2026 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2027 .x(300)
2028 .y(400))
2029 .build()));
2030 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2031
2032 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002033 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002034 injectMotionEvent(mDispatcher,
2035 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2036 AINPUT_SOURCE_MOUSE)
2037 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2038 .x(900)
2039 .y(400))
2040 .build()));
2041 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2042 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2043 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2044 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2045 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2046 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2047}
2048
2049// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2050// directly in this test.
2051TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002052 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002053 sp<FakeWindowHandle> window =
2054 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2055 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002056
2057 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2058
2059 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2060
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002061 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002062 injectMotionEvent(mDispatcher,
2063 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2064 AINPUT_SOURCE_MOUSE)
2065 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2066 .x(300)
2067 .y(400))
2068 .build()));
2069 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2070 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2071
2072 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002073 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002074 injectMotionEvent(mDispatcher,
2075 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2076 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2077 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2078 .x(300)
2079 .y(400))
2080 .build()));
2081 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2082
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002083 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002084 injectMotionEvent(mDispatcher,
2085 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2086 AINPUT_SOURCE_MOUSE)
2087 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2088 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2089 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2090 .x(300)
2091 .y(400))
2092 .build()));
2093 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2094 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2095
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002096 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002097 injectMotionEvent(mDispatcher,
2098 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2099 AINPUT_SOURCE_MOUSE)
2100 .buttonState(0)
2101 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2102 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2103 .x(300)
2104 .y(400))
2105 .build()));
2106 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2107 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2108
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002109 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002110 injectMotionEvent(mDispatcher,
2111 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2112 .buttonState(0)
2113 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2114 .x(300)
2115 .y(400))
2116 .build()));
2117 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2118
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002119 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002120 injectMotionEvent(mDispatcher,
2121 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2122 AINPUT_SOURCE_MOUSE)
2123 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2124 .x(300)
2125 .y(400))
2126 .build()));
2127 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2128 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2129}
2130
Garfield Tan00f511d2019-06-12 16:55:40 -07002131TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002132 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002133
2134 sp<FakeWindowHandle> windowLeft =
2135 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2136 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002137 sp<FakeWindowHandle> windowRight =
2138 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2139 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002140
2141 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2142
Arthur Hung72d8dc32020-03-28 00:48:39 +00002143 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002144
2145 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2146 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002147 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002148 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002149 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002150 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002151 windowRight->assertNoEvents();
2152}
2153
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002154TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002155 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002156 sp<FakeWindowHandle> window =
2157 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002158 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002159
Arthur Hung72d8dc32020-03-28 00:48:39 +00002160 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002161 setFocusedWindow(window);
2162
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002163 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002164
2165 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2166 mDispatcher->notifyKey(&keyArgs);
2167
2168 // Window should receive key down event.
2169 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2170
2171 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2172 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002173 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002174 mDispatcher->notifyDeviceReset(&args);
2175 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2176 AKEY_EVENT_FLAG_CANCELED);
2177}
2178
2179TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002180 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002181 sp<FakeWindowHandle> window =
2182 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2183
Arthur Hung72d8dc32020-03-28 00:48:39 +00002184 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002185
2186 NotifyMotionArgs motionArgs =
2187 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2188 ADISPLAY_ID_DEFAULT);
2189 mDispatcher->notifyMotion(&motionArgs);
2190
2191 // Window should receive motion down event.
2192 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2193
2194 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2195 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002196 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002197 mDispatcher->notifyDeviceReset(&args);
2198 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2199 0 /*expectedFlags*/);
2200}
2201
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002202TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
2203 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2204 sp<FakeWindowHandle> window =
2205 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2206 window->setFocusable(true);
2207
2208 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2209 setFocusedWindow(window);
2210
2211 window->consumeFocusEvent(true);
2212
2213 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2214 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
2215 const nsecs_t injectTime = keyArgs.eventTime;
2216 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
2217 mDispatcher->notifyKey(&keyArgs);
2218 // The dispatching time should be always greater than or equal to intercept key timeout.
2219 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2220 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
2221 std::chrono::nanoseconds(interceptKeyTimeout).count());
2222}
2223
2224TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
2225 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2226 sp<FakeWindowHandle> window =
2227 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2228 window->setFocusable(true);
2229
2230 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2231 setFocusedWindow(window);
2232
2233 window->consumeFocusEvent(true);
2234
2235 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2236 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2237 mFakePolicy->setInterceptKeyTimeout(150ms);
2238 mDispatcher->notifyKey(&keyDown);
2239 mDispatcher->notifyKey(&keyUp);
2240
2241 // Window should receive key event immediately when same key up.
2242 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2243 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2244}
2245
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002246/**
2247 * Ensure the correct coordinate spaces are used by InputDispatcher.
2248 *
2249 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2250 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2251 * space.
2252 */
2253class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2254public:
2255 void SetUp() override {
2256 InputDispatcherTest::SetUp();
2257 mDisplayInfos.clear();
2258 mWindowInfos.clear();
2259 }
2260
2261 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2262 gui::DisplayInfo info;
2263 info.displayId = displayId;
2264 info.transform = transform;
2265 mDisplayInfos.push_back(std::move(info));
2266 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2267 }
2268
2269 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2270 mWindowInfos.push_back(*windowHandle->getInfo());
2271 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2272 }
2273
2274 // Set up a test scenario where the display has a scaled projection and there are two windows
2275 // on the display.
2276 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2277 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2278 // respectively.
2279 ui::Transform displayTransform;
2280 displayTransform.set(2, 0, 0, 4);
2281 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2282
2283 std::shared_ptr<FakeApplicationHandle> application =
2284 std::make_shared<FakeApplicationHandle>();
2285
2286 // Add two windows to the display. Their frames are represented in the display space.
2287 sp<FakeWindowHandle> firstWindow =
2288 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002289 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2290 addWindow(firstWindow);
2291
2292 sp<FakeWindowHandle> secondWindow =
2293 new FakeWindowHandle(application, mDispatcher, "Second Window",
2294 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002295 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2296 addWindow(secondWindow);
2297 return {std::move(firstWindow), std::move(secondWindow)};
2298 }
2299
2300private:
2301 std::vector<gui::DisplayInfo> mDisplayInfos;
2302 std::vector<gui::WindowInfo> mWindowInfos;
2303};
2304
2305TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2306 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2307 // Send down to the first window. The point is represented in the display space. The point is
2308 // selected so that if the hit test was done with the transform applied to it, then it would
2309 // end up in the incorrect window.
2310 NotifyMotionArgs downMotionArgs =
2311 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2312 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2313 mDispatcher->notifyMotion(&downMotionArgs);
2314
2315 firstWindow->consumeMotionDown();
2316 secondWindow->assertNoEvents();
2317}
2318
2319// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2320// the event should be treated as being in the logical display space.
2321TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2322 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2323 // Send down to the first window. The point is represented in the logical display space. The
2324 // point is selected so that if the hit test was done in logical display space, then it would
2325 // end up in the incorrect window.
2326 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2327 PointF{75 * 2, 55 * 4});
2328
2329 firstWindow->consumeMotionDown();
2330 secondWindow->assertNoEvents();
2331}
2332
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002333// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2334// event should be treated as being in the logical display space.
2335TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2336 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2337
2338 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2339 ui::Transform injectedEventTransform;
2340 injectedEventTransform.set(matrix);
2341 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2342 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2343
2344 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2345 .displayId(ADISPLAY_ID_DEFAULT)
2346 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2347 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2348 .x(untransformedPoint.x)
2349 .y(untransformedPoint.y))
2350 .build();
2351 event.transform(matrix);
2352
2353 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2354 InputEventInjectionSync::WAIT_FOR_RESULT);
2355
2356 firstWindow->consumeMotionDown();
2357 secondWindow->assertNoEvents();
2358}
2359
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002360TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2361 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2362
2363 // Send down to the second window.
2364 NotifyMotionArgs downMotionArgs =
2365 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2366 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2367 mDispatcher->notifyMotion(&downMotionArgs);
2368
2369 firstWindow->assertNoEvents();
2370 const MotionEvent* event = secondWindow->consumeMotion();
2371 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2372
2373 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2374 EXPECT_EQ(300, event->getRawX(0));
2375 EXPECT_EQ(880, event->getRawY(0));
2376
2377 // Ensure that the x and y values are in the window's coordinate space.
2378 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2379 // the logical display space. This will be the origin of the window space.
2380 EXPECT_EQ(100, event->getX(0));
2381 EXPECT_EQ(80, event->getY(0));
2382}
2383
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002384using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2385 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002386
2387class TransferTouchFixture : public InputDispatcherTest,
2388 public ::testing::WithParamInterface<TransferFunction> {};
2389
2390TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002391 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002392
2393 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002394 sp<FakeWindowHandle> firstWindow =
2395 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2396 sp<FakeWindowHandle> secondWindow =
2397 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002398
2399 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002400 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002401
2402 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002403 NotifyMotionArgs downMotionArgs =
2404 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2405 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002406 mDispatcher->notifyMotion(&downMotionArgs);
2407 // Only the first window should get the down event
2408 firstWindow->consumeMotionDown();
2409 secondWindow->assertNoEvents();
2410
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002411 // Transfer touch to the second window
2412 TransferFunction f = GetParam();
2413 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2414 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002415 // The first window gets cancel and the second gets down
2416 firstWindow->consumeMotionCancel();
2417 secondWindow->consumeMotionDown();
2418
2419 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002420 NotifyMotionArgs upMotionArgs =
2421 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2422 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002423 mDispatcher->notifyMotion(&upMotionArgs);
2424 // The first window gets no events and the second gets up
2425 firstWindow->assertNoEvents();
2426 secondWindow->consumeMotionUp();
2427}
2428
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002429/**
2430 * When 'transferTouch' API is invoked, dispatcher needs to find the "best" window to take touch
2431 * from. When we have spy windows, there are several windows to choose from: either spy, or the
2432 * 'real' (non-spy) window. Always prefer the 'real' window because that's what would be most
2433 * natural to the user.
2434 * In this test, we are sending a pointer to both spy window and first window. We then try to
2435 * transfer touch to the second window. The dispatcher should identify the first window as the
2436 * one that should lose the gesture, and therefore the action should be to move the gesture from
2437 * the first window to the second.
2438 * The main goal here is to test the behaviour of 'transferTouch' API, but it's still valid to test
2439 * the other API, as well.
2440 */
2441TEST_P(TransferTouchFixture, TransferTouch_MultipleWindowsWithSpy) {
2442 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2443
2444 // Create a couple of windows + a spy window
2445 sp<FakeWindowHandle> spyWindow =
2446 new FakeWindowHandle(application, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
2447 spyWindow->setTrustedOverlay(true);
2448 spyWindow->setSpy(true);
2449 sp<FakeWindowHandle> firstWindow =
2450 new FakeWindowHandle(application, mDispatcher, "First", ADISPLAY_ID_DEFAULT);
2451 sp<FakeWindowHandle> secondWindow =
2452 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
2453
2454 // Add the windows to the dispatcher
2455 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyWindow, firstWindow, secondWindow}}});
2456
2457 // Send down to the first window
2458 NotifyMotionArgs downMotionArgs =
2459 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2460 ADISPLAY_ID_DEFAULT);
2461 mDispatcher->notifyMotion(&downMotionArgs);
2462 // Only the first window and spy should get the down event
2463 spyWindow->consumeMotionDown();
2464 firstWindow->consumeMotionDown();
2465
2466 // Transfer touch to the second window. Non-spy window should be preferred over the spy window
2467 // if f === 'transferTouch'.
2468 TransferFunction f = GetParam();
2469 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2470 ASSERT_TRUE(success);
2471 // The first window gets cancel and the second gets down
2472 firstWindow->consumeMotionCancel();
2473 secondWindow->consumeMotionDown();
2474
2475 // Send up event to the second window
2476 NotifyMotionArgs upMotionArgs =
2477 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2478 ADISPLAY_ID_DEFAULT);
2479 mDispatcher->notifyMotion(&upMotionArgs);
2480 // The first window gets no events and the second+spy get up
2481 firstWindow->assertNoEvents();
2482 spyWindow->consumeMotionUp();
2483 secondWindow->consumeMotionUp();
2484}
2485
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002486TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002487 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002488
2489 PointF touchPoint = {10, 10};
2490
2491 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002492 sp<FakeWindowHandle> firstWindow =
2493 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002494 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002495 sp<FakeWindowHandle> secondWindow =
2496 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002497 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002498
2499 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002500 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002501
2502 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002503 NotifyMotionArgs downMotionArgs =
2504 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2505 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002506 mDispatcher->notifyMotion(&downMotionArgs);
2507 // Only the first window should get the down event
2508 firstWindow->consumeMotionDown();
2509 secondWindow->assertNoEvents();
2510
2511 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002512 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002513 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002514 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002515 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2516 // Only the first window should get the pointer down event
2517 firstWindow->consumeMotionPointerDown(1);
2518 secondWindow->assertNoEvents();
2519
2520 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002521 TransferFunction f = GetParam();
2522 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2523 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002524 // The first window gets cancel and the second gets down and pointer down
2525 firstWindow->consumeMotionCancel();
2526 secondWindow->consumeMotionDown();
2527 secondWindow->consumeMotionPointerDown(1);
2528
2529 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002530 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002531 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002532 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002533 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2534 // The first window gets nothing and the second gets pointer up
2535 firstWindow->assertNoEvents();
2536 secondWindow->consumeMotionPointerUp(1);
2537
2538 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002539 NotifyMotionArgs upMotionArgs =
2540 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2541 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002542 mDispatcher->notifyMotion(&upMotionArgs);
2543 // The first window gets nothing and the second gets up
2544 firstWindow->assertNoEvents();
2545 secondWindow->consumeMotionUp();
2546}
2547
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002548// For the cases of single pointer touch and two pointers non-split touch, the api's
2549// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2550// for the case where there are multiple pointers split across several windows.
2551INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2552 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002553 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2554 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002555 return dispatcher->transferTouch(destChannelToken,
2556 ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002557 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002558 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2559 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002560 return dispatcher->transferTouchFocus(from, to,
2561 false /*isDragAndDrop*/);
2562 }));
2563
Svet Ganov5d3bc372020-01-26 23:11:07 -08002564TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002565 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002566
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002567 sp<FakeWindowHandle> firstWindow =
2568 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002569 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002570
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002571 sp<FakeWindowHandle> secondWindow =
2572 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002573 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002574
2575 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002576 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002577
2578 PointF pointInFirst = {300, 200};
2579 PointF pointInSecond = {300, 600};
2580
2581 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002582 NotifyMotionArgs firstDownMotionArgs =
2583 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2584 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002585 mDispatcher->notifyMotion(&firstDownMotionArgs);
2586 // Only the first window should get the down event
2587 firstWindow->consumeMotionDown();
2588 secondWindow->assertNoEvents();
2589
2590 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002591 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002592 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002593 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002594 mDispatcher->notifyMotion(&secondDownMotionArgs);
2595 // The first window gets a move and the second a down
2596 firstWindow->consumeMotionMove();
2597 secondWindow->consumeMotionDown();
2598
2599 // Transfer touch focus to the second window
2600 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2601 // The first window gets cancel and the new gets pointer down (it already saw down)
2602 firstWindow->consumeMotionCancel();
2603 secondWindow->consumeMotionPointerDown(1);
2604
2605 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002606 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002607 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002608 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002609 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2610 // The first window gets nothing and the second gets pointer up
2611 firstWindow->assertNoEvents();
2612 secondWindow->consumeMotionPointerUp(1);
2613
2614 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002615 NotifyMotionArgs upMotionArgs =
2616 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2617 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002618 mDispatcher->notifyMotion(&upMotionArgs);
2619 // The first window gets nothing and the second gets up
2620 firstWindow->assertNoEvents();
2621 secondWindow->consumeMotionUp();
2622}
2623
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002624// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2625// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2626// touch is not supported, so the touch should continue on those windows and the transferred-to
2627// window should get nothing.
2628TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2629 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2630
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002631 sp<FakeWindowHandle> firstWindow =
2632 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2633 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002634
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002635 sp<FakeWindowHandle> secondWindow =
2636 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2637 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002638
2639 // Add the windows to the dispatcher
2640 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2641
2642 PointF pointInFirst = {300, 200};
2643 PointF pointInSecond = {300, 600};
2644
2645 // Send down to the first window
2646 NotifyMotionArgs firstDownMotionArgs =
2647 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2648 ADISPLAY_ID_DEFAULT, {pointInFirst});
2649 mDispatcher->notifyMotion(&firstDownMotionArgs);
2650 // Only the first window should get the down event
2651 firstWindow->consumeMotionDown();
2652 secondWindow->assertNoEvents();
2653
2654 // Send down to the second window
2655 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002656 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002657 {pointInFirst, pointInSecond});
2658 mDispatcher->notifyMotion(&secondDownMotionArgs);
2659 // The first window gets a move and the second a down
2660 firstWindow->consumeMotionMove();
2661 secondWindow->consumeMotionDown();
2662
2663 // Transfer touch focus to the second window
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002664 const bool transferred =
2665 mDispatcher->transferTouch(secondWindow->getToken(), ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002666 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2667 ASSERT_FALSE(transferred);
2668 firstWindow->assertNoEvents();
2669 secondWindow->assertNoEvents();
2670
2671 // The rest of the dispatch should proceed as normal
2672 // Send pointer up to the second window
2673 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002674 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002675 {pointInFirst, pointInSecond});
2676 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2677 // The first window gets MOVE and the second gets pointer up
2678 firstWindow->consumeMotionMove();
2679 secondWindow->consumeMotionUp();
2680
2681 // Send up event to the first window
2682 NotifyMotionArgs upMotionArgs =
2683 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2684 ADISPLAY_ID_DEFAULT);
2685 mDispatcher->notifyMotion(&upMotionArgs);
2686 // The first window gets nothing and the second gets up
2687 firstWindow->consumeMotionUp();
2688 secondWindow->assertNoEvents();
2689}
2690
Arthur Hungabbb9d82021-09-01 14:52:30 +00002691// This case will create two windows and one mirrored window on the default display and mirror
2692// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2693// the windows info of second display before default display.
2694TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2695 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2696 sp<FakeWindowHandle> firstWindowInPrimary =
2697 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2698 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002699 sp<FakeWindowHandle> secondWindowInPrimary =
2700 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2701 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002702
2703 sp<FakeWindowHandle> mirrorWindowInPrimary =
2704 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2705 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002706
2707 sp<FakeWindowHandle> firstWindowInSecondary =
2708 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2709 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002710
2711 sp<FakeWindowHandle> secondWindowInSecondary =
2712 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2713 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002714
2715 // Update window info, let it find window handle of second display first.
2716 mDispatcher->setInputWindows(
2717 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2718 {ADISPLAY_ID_DEFAULT,
2719 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2720
2721 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2722 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2723 {50, 50}))
2724 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2725
2726 // Window should receive motion event.
2727 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2728
2729 // Transfer touch focus
2730 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2731 secondWindowInPrimary->getToken()));
2732 // The first window gets cancel.
2733 firstWindowInPrimary->consumeMotionCancel();
2734 secondWindowInPrimary->consumeMotionDown();
2735
2736 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2737 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2738 ADISPLAY_ID_DEFAULT, {150, 50}))
2739 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2740 firstWindowInPrimary->assertNoEvents();
2741 secondWindowInPrimary->consumeMotionMove();
2742
2743 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2744 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2745 {150, 50}))
2746 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2747 firstWindowInPrimary->assertNoEvents();
2748 secondWindowInPrimary->consumeMotionUp();
2749}
2750
2751// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2752// 'transferTouch' api.
2753TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2754 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2755 sp<FakeWindowHandle> firstWindowInPrimary =
2756 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2757 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002758 sp<FakeWindowHandle> secondWindowInPrimary =
2759 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2760 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002761
2762 sp<FakeWindowHandle> mirrorWindowInPrimary =
2763 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2764 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002765
2766 sp<FakeWindowHandle> firstWindowInSecondary =
2767 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2768 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002769
2770 sp<FakeWindowHandle> secondWindowInSecondary =
2771 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2772 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002773
2774 // Update window info, let it find window handle of second display first.
2775 mDispatcher->setInputWindows(
2776 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2777 {ADISPLAY_ID_DEFAULT,
2778 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2779
2780 // Touch on second display.
2781 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2782 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2783 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2784
2785 // Window should receive motion event.
2786 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2787
2788 // Transfer touch focus
Siarhei Vishniakou7ae7afd2022-03-31 15:26:13 -07002789 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken(), SECOND_DISPLAY_ID));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002790
2791 // The first window gets cancel.
2792 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2793 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2794
2795 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2796 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2797 SECOND_DISPLAY_ID, {150, 50}))
2798 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2799 firstWindowInPrimary->assertNoEvents();
2800 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2801
2802 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2803 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2804 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2805 firstWindowInPrimary->assertNoEvents();
2806 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2807}
2808
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002809TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002810 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002811 sp<FakeWindowHandle> window =
2812 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2813
Vishnu Nair47074b82020-08-14 11:54:47 -07002814 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002815 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002816 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002817
2818 window->consumeFocusEvent(true);
2819
2820 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2821 mDispatcher->notifyKey(&keyArgs);
2822
2823 // Window should receive key down event.
2824 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2825}
2826
2827TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002828 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002829 sp<FakeWindowHandle> window =
2830 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2831
Arthur Hung72d8dc32020-03-28 00:48:39 +00002832 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002833
2834 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2835 mDispatcher->notifyKey(&keyArgs);
2836 mDispatcher->waitForIdle();
2837
2838 window->assertNoEvents();
2839}
2840
2841// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2842TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002843 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002844 sp<FakeWindowHandle> window =
2845 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2846
Arthur Hung72d8dc32020-03-28 00:48:39 +00002847 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002848
2849 // Send key
2850 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2851 mDispatcher->notifyKey(&keyArgs);
2852 // Send motion
2853 NotifyMotionArgs motionArgs =
2854 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2855 ADISPLAY_ID_DEFAULT);
2856 mDispatcher->notifyMotion(&motionArgs);
2857
2858 // Window should receive only the motion event
2859 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2860 window->assertNoEvents(); // Key event or focus event will not be received
2861}
2862
arthurhungea3f4fc2020-12-21 23:18:53 +08002863TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2864 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2865
arthurhungea3f4fc2020-12-21 23:18:53 +08002866 sp<FakeWindowHandle> firstWindow =
2867 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2868 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08002869
arthurhungea3f4fc2020-12-21 23:18:53 +08002870 sp<FakeWindowHandle> secondWindow =
2871 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2872 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08002873
2874 // Add the windows to the dispatcher
2875 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2876
2877 PointF pointInFirst = {300, 200};
2878 PointF pointInSecond = {300, 600};
2879
2880 // Send down to the first window
2881 NotifyMotionArgs firstDownMotionArgs =
2882 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2883 ADISPLAY_ID_DEFAULT, {pointInFirst});
2884 mDispatcher->notifyMotion(&firstDownMotionArgs);
2885 // Only the first window should get the down event
2886 firstWindow->consumeMotionDown();
2887 secondWindow->assertNoEvents();
2888
2889 // Send down to the second window
2890 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002891 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08002892 {pointInFirst, pointInSecond});
2893 mDispatcher->notifyMotion(&secondDownMotionArgs);
2894 // The first window gets a move and the second a down
2895 firstWindow->consumeMotionMove();
2896 secondWindow->consumeMotionDown();
2897
2898 // Send pointer cancel to the second window
2899 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002900 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08002901 {pointInFirst, pointInSecond});
2902 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2903 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2904 // The first window gets move and the second gets cancel.
2905 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2906 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2907
2908 // Send up event.
2909 NotifyMotionArgs upMotionArgs =
2910 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2911 ADISPLAY_ID_DEFAULT);
2912 mDispatcher->notifyMotion(&upMotionArgs);
2913 // The first window gets up and the second gets nothing.
2914 firstWindow->consumeMotionUp();
2915 secondWindow->assertNoEvents();
2916}
2917
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002918TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2919 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2920
2921 sp<FakeWindowHandle> window =
2922 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2923 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2924 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2925 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2926 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2927
2928 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2929 window->assertNoEvents();
2930 mDispatcher->waitForIdle();
2931}
2932
chaviwd1c23182019-12-20 18:44:56 -08002933class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002934public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002935 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002936 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07002937 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002938 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002939 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002940 }
2941
chaviwd1c23182019-12-20 18:44:56 -08002942 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2943
2944 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2945 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2946 expectedDisplayId, expectedFlags);
2947 }
2948
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002949 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2950
2951 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2952
chaviwd1c23182019-12-20 18:44:56 -08002953 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2954 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2955 expectedDisplayId, expectedFlags);
2956 }
2957
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002958 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2959 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2960 expectedDisplayId, expectedFlags);
2961 }
2962
chaviwd1c23182019-12-20 18:44:56 -08002963 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2964 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2965 expectedDisplayId, expectedFlags);
2966 }
2967
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002968 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2969 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2970 expectedDisplayId, expectedFlags);
2971 }
2972
Arthur Hungfbfa5722021-11-16 02:45:54 +00002973 void consumeMotionPointerDown(int32_t pointerIdx) {
2974 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2975 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2976 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2977 0 /*expectedFlags*/);
2978 }
2979
Evan Rosky84f07f02021-04-16 10:42:42 -07002980 MotionEvent* consumeMotion() {
2981 InputEvent* event = mInputReceiver->consume();
2982 if (!event) {
2983 ADD_FAILURE() << "No event was produced";
2984 return nullptr;
2985 }
2986 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2987 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2988 return nullptr;
2989 }
2990 return static_cast<MotionEvent*>(event);
2991 }
2992
chaviwd1c23182019-12-20 18:44:56 -08002993 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2994
2995private:
2996 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002997};
2998
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002999using InputDispatcherMonitorTest = InputDispatcherTest;
3000
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003001/**
3002 * Two entities that receive touch: A window, and a global monitor.
3003 * The touch goes to the window, and then the window disappears.
3004 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
3005 * for the monitor, as well.
3006 * 1. foregroundWindow
3007 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
3008 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003009TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003010 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3011 sp<FakeWindowHandle> window =
3012 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
3013
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003014 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00003015
3016 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3017 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3018 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3019 {100, 200}))
3020 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3021
3022 // Both the foreground window and the global monitor should receive the touch down
3023 window->consumeMotionDown();
3024 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3025
3026 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3027 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3028 ADISPLAY_ID_DEFAULT, {110, 200}))
3029 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3030
3031 window->consumeMotionMove();
3032 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3033
3034 // Now the foreground window goes away
3035 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
3036 window->consumeMotionCancel();
3037 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
3038
3039 // If more events come in, there will be no more foreground window to send them to. This will
3040 // cause a cancel for the monitor, as well.
3041 ASSERT_EQ(InputEventInjectionResult::FAILED,
3042 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3043 ADISPLAY_ID_DEFAULT, {120, 200}))
3044 << "Injection should fail because the window was removed";
3045 window->assertNoEvents();
3046 // Global monitor now gets the cancel
3047 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3048}
3049
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003050TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07003051 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003052 sp<FakeWindowHandle> window =
3053 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003054 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003055
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003056 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003057
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003058 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003059 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003060 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003061 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003062 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003063}
3064
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003065TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3066 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003067
Chris Yea209fde2020-07-22 13:54:51 -07003068 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003069 sp<FakeWindowHandle> window =
3070 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003071 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003072
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003073 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003074 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003075 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003076 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003077 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003078
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003079 // Pilfer pointers from the monitor.
3080 // This should not do anything and the window should continue to receive events.
3081 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003082
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003083 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003084 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3085 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003086 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003087
3088 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3089 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003090}
3091
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003092TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003093 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3094 sp<FakeWindowHandle> window =
3095 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3096 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3097 window->setWindowOffset(20, 40);
3098 window->setWindowTransform(0, 1, -1, 0);
3099
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003100 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003101
3102 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3103 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3104 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3105 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3106 MotionEvent* event = monitor.consumeMotion();
3107 // Even though window has transform, gesture monitor must not.
3108 ASSERT_EQ(ui::Transform(), event->getTransform());
3109}
3110
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003111TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003112 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003113 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003114
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003115 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003116 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003117 << "Injection should fail if there is a monitor, but no touchable window";
3118 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003119}
3120
chaviw81e2bb92019-12-18 15:03:51 -08003121TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003122 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08003123 sp<FakeWindowHandle> window =
3124 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3125
Arthur Hung72d8dc32020-03-28 00:48:39 +00003126 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003127
3128 NotifyMotionArgs motionArgs =
3129 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3130 ADISPLAY_ID_DEFAULT);
3131
3132 mDispatcher->notifyMotion(&motionArgs);
3133 // Window should receive motion down event.
3134 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3135
3136 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003137 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003138 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3139 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3140 motionArgs.pointerCoords[0].getX() - 10);
3141
3142 mDispatcher->notifyMotion(&motionArgs);
3143 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3144 0 /*expectedFlags*/);
3145}
3146
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003147/**
3148 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3149 * the device default right away. In the test scenario, we check both the default value,
3150 * and the action of enabling / disabling.
3151 */
3152TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003153 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003154 sp<FakeWindowHandle> window =
3155 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003156 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003157
3158 // Set focused application.
3159 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003160 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003161
3162 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003163 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003164 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003165 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3166
3167 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003168 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003169 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003170 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3171
3172 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003173 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3174 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003175 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003176 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003177 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003178 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003179 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3180
3181 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003182 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003183 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003184 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3185
3186 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003187 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3188 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003189 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003190 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003191 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003192 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003193 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3194
3195 window->assertNoEvents();
3196}
3197
Gang Wange9087892020-01-07 12:17:14 -05003198TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003199 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003200 sp<FakeWindowHandle> window =
3201 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3202
3203 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003204 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003205
Arthur Hung72d8dc32020-03-28 00:48:39 +00003206 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003207 setFocusedWindow(window);
3208
Gang Wange9087892020-01-07 12:17:14 -05003209 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3210
3211 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3212 mDispatcher->notifyKey(&keyArgs);
3213
3214 InputEvent* event = window->consume();
3215 ASSERT_NE(event, nullptr);
3216
3217 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3218 ASSERT_NE(verified, nullptr);
3219 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3220
3221 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3222 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3223 ASSERT_EQ(keyArgs.source, verified->source);
3224 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3225
3226 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3227
3228 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003229 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003230 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003231 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3232 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3233 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3234 ASSERT_EQ(0, verifiedKey.repeatCount);
3235}
3236
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003237TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003238 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003239 sp<FakeWindowHandle> window =
3240 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3241
3242 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3243
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003244 ui::Transform transform;
3245 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3246
3247 gui::DisplayInfo displayInfo;
3248 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3249 displayInfo.transform = transform;
3250
3251 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003252
3253 NotifyMotionArgs motionArgs =
3254 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3255 ADISPLAY_ID_DEFAULT);
3256 mDispatcher->notifyMotion(&motionArgs);
3257
3258 InputEvent* event = window->consume();
3259 ASSERT_NE(event, nullptr);
3260
3261 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3262 ASSERT_NE(verified, nullptr);
3263 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3264
3265 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3266 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3267 EXPECT_EQ(motionArgs.source, verified->source);
3268 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3269
3270 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3271
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003272 const vec2 rawXY =
3273 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3274 motionArgs.pointerCoords[0].getXYValue());
3275 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3276 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003277 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003278 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003279 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003280 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3281 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3282}
3283
chaviw09c8d2d2020-08-24 15:48:26 -07003284/**
3285 * Ensure that separate calls to sign the same data are generating the same key.
3286 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3287 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3288 * tests.
3289 */
3290TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3291 KeyEvent event = getTestKeyEvent();
3292 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3293
3294 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3295 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3296 ASSERT_EQ(hmac1, hmac2);
3297}
3298
3299/**
3300 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3301 */
3302TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3303 KeyEvent event = getTestKeyEvent();
3304 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3305 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3306
3307 verifiedEvent.deviceId += 1;
3308 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3309
3310 verifiedEvent.source += 1;
3311 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3312
3313 verifiedEvent.eventTimeNanos += 1;
3314 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3315
3316 verifiedEvent.displayId += 1;
3317 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3318
3319 verifiedEvent.action += 1;
3320 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3321
3322 verifiedEvent.downTimeNanos += 1;
3323 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3324
3325 verifiedEvent.flags += 1;
3326 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3327
3328 verifiedEvent.keyCode += 1;
3329 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3330
3331 verifiedEvent.scanCode += 1;
3332 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3333
3334 verifiedEvent.metaState += 1;
3335 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3336
3337 verifiedEvent.repeatCount += 1;
3338 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3339}
3340
Vishnu Nair958da932020-08-21 17:12:37 -07003341TEST_F(InputDispatcherTest, SetFocusedWindow) {
3342 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3343 sp<FakeWindowHandle> windowTop =
3344 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3345 sp<FakeWindowHandle> windowSecond =
3346 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3347 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3348
3349 // Top window is also focusable but is not granted focus.
3350 windowTop->setFocusable(true);
3351 windowSecond->setFocusable(true);
3352 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3353 setFocusedWindow(windowSecond);
3354
3355 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003356 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3357 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003358
3359 // Focused window should receive event.
3360 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3361 windowTop->assertNoEvents();
3362}
3363
3364TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3365 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3366 sp<FakeWindowHandle> window =
3367 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3368 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3369
3370 window->setFocusable(true);
3371 // Release channel for window is no longer valid.
3372 window->releaseChannel();
3373 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3374 setFocusedWindow(window);
3375
3376 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003377 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3378 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003379
3380 // window channel is invalid, so it should not receive any input event.
3381 window->assertNoEvents();
3382}
3383
3384TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3385 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3386 sp<FakeWindowHandle> window =
3387 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003388 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003389 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3390
Vishnu Nair958da932020-08-21 17:12:37 -07003391 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3392 setFocusedWindow(window);
3393
3394 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003395 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3396 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003397
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003398 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003399 window->assertNoEvents();
3400}
3401
3402TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3403 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3404 sp<FakeWindowHandle> windowTop =
3405 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3406 sp<FakeWindowHandle> windowSecond =
3407 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3408 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3409
3410 windowTop->setFocusable(true);
3411 windowSecond->setFocusable(true);
3412 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3413 setFocusedWindow(windowTop);
3414 windowTop->consumeFocusEvent(true);
3415
3416 setFocusedWindow(windowSecond, windowTop);
3417 windowSecond->consumeFocusEvent(true);
3418 windowTop->consumeFocusEvent(false);
3419
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003420 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3421 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003422
3423 // Focused window should receive event.
3424 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3425}
3426
3427TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3428 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3429 sp<FakeWindowHandle> windowTop =
3430 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3431 sp<FakeWindowHandle> windowSecond =
3432 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3433 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3434
3435 windowTop->setFocusable(true);
3436 windowSecond->setFocusable(true);
3437 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3438 setFocusedWindow(windowSecond, windowTop);
3439
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003440 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3441 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003442
3443 // Event should be dropped.
3444 windowTop->assertNoEvents();
3445 windowSecond->assertNoEvents();
3446}
3447
3448TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3449 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3450 sp<FakeWindowHandle> window =
3451 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3452 sp<FakeWindowHandle> previousFocusedWindow =
3453 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3454 ADISPLAY_ID_DEFAULT);
3455 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3456
3457 window->setFocusable(true);
3458 previousFocusedWindow->setFocusable(true);
3459 window->setVisible(false);
3460 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3461 setFocusedWindow(previousFocusedWindow);
3462 previousFocusedWindow->consumeFocusEvent(true);
3463
3464 // Requesting focus on invisible window takes focus from currently focused window.
3465 setFocusedWindow(window);
3466 previousFocusedWindow->consumeFocusEvent(false);
3467
3468 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003469 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003470 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003471 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003472
3473 // Window does not get focus event or key down.
3474 window->assertNoEvents();
3475
3476 // Window becomes visible.
3477 window->setVisible(true);
3478 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3479
3480 // Window receives focus event.
3481 window->consumeFocusEvent(true);
3482 // Focused window receives key down.
3483 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3484}
3485
Vishnu Nair599f1412021-06-21 10:39:58 -07003486TEST_F(InputDispatcherTest, DisplayRemoved) {
3487 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3488 sp<FakeWindowHandle> window =
3489 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3490 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3491
3492 // window is granted focus.
3493 window->setFocusable(true);
3494 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3495 setFocusedWindow(window);
3496 window->consumeFocusEvent(true);
3497
3498 // When a display is removed window loses focus.
3499 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3500 window->consumeFocusEvent(false);
3501}
3502
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003503/**
3504 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3505 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3506 * of the 'slipperyEnterWindow'.
3507 *
3508 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3509 * a way so that the touched location is no longer covered by the top window.
3510 *
3511 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3512 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3513 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3514 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3515 * with ACTION_DOWN).
3516 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3517 * window moved itself away from the touched location and had Flag::SLIPPERY.
3518 *
3519 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3520 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3521 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3522 *
3523 * In this test, we ensure that the event received by the bottom window has
3524 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3525 */
3526TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3527 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3528 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3529
3530 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3531 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3532
3533 sp<FakeWindowHandle> slipperyExitWindow =
3534 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003535 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003536 // Make sure this one overlaps the bottom window
3537 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3538 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3539 // one. Windows with the same owner are not considered to be occluding each other.
3540 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3541
3542 sp<FakeWindowHandle> slipperyEnterWindow =
3543 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3544 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3545
3546 mDispatcher->setInputWindows(
3547 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3548
3549 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3550 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3551 ADISPLAY_ID_DEFAULT, {{50, 50}});
3552 mDispatcher->notifyMotion(&args);
3553 slipperyExitWindow->consumeMotionDown();
3554 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3555 mDispatcher->setInputWindows(
3556 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3557
3558 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3559 ADISPLAY_ID_DEFAULT, {{51, 51}});
3560 mDispatcher->notifyMotion(&args);
3561
3562 slipperyExitWindow->consumeMotionCancel();
3563
3564 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3565 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3566}
3567
Garfield Tan1c7bc862020-01-28 13:24:04 -08003568class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3569protected:
3570 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3571 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3572
Chris Yea209fde2020-07-22 13:54:51 -07003573 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003574 sp<FakeWindowHandle> mWindow;
3575
3576 virtual void SetUp() override {
3577 mFakePolicy = new FakeInputDispatcherPolicy();
3578 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003579 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003580 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3581 ASSERT_EQ(OK, mDispatcher->start());
3582
3583 setUpWindow();
3584 }
3585
3586 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003587 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003588 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3589
Vishnu Nair47074b82020-08-14 11:54:47 -07003590 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003591 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003592 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003593 mWindow->consumeFocusEvent(true);
3594 }
3595
Chris Ye2ad95392020-09-01 13:44:44 -07003596 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003597 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003598 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003599 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3600 mDispatcher->notifyKey(&keyArgs);
3601
3602 // Window should receive key down event.
3603 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3604 }
3605
3606 void expectKeyRepeatOnce(int32_t repeatCount) {
3607 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3608 InputEvent* repeatEvent = mWindow->consume();
3609 ASSERT_NE(nullptr, repeatEvent);
3610
3611 uint32_t eventType = repeatEvent->getType();
3612 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3613
3614 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3615 uint32_t eventAction = repeatKeyEvent->getAction();
3616 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3617 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3618 }
3619
Chris Ye2ad95392020-09-01 13:44:44 -07003620 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003621 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003622 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003623 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3624 mDispatcher->notifyKey(&keyArgs);
3625
3626 // Window should receive key down event.
3627 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3628 0 /*expectedFlags*/);
3629 }
3630};
3631
3632TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003633 sendAndConsumeKeyDown(1 /* deviceId */);
3634 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3635 expectKeyRepeatOnce(repeatCount);
3636 }
3637}
3638
3639TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3640 sendAndConsumeKeyDown(1 /* deviceId */);
3641 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3642 expectKeyRepeatOnce(repeatCount);
3643 }
3644 sendAndConsumeKeyDown(2 /* deviceId */);
3645 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003646 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3647 expectKeyRepeatOnce(repeatCount);
3648 }
3649}
3650
3651TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003652 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003653 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003654 sendAndConsumeKeyUp(1 /* deviceId */);
3655 mWindow->assertNoEvents();
3656}
3657
3658TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3659 sendAndConsumeKeyDown(1 /* deviceId */);
3660 expectKeyRepeatOnce(1 /*repeatCount*/);
3661 sendAndConsumeKeyDown(2 /* deviceId */);
3662 expectKeyRepeatOnce(1 /*repeatCount*/);
3663 // Stale key up from device 1.
3664 sendAndConsumeKeyUp(1 /* deviceId */);
3665 // Device 2 is still down, keep repeating
3666 expectKeyRepeatOnce(2 /*repeatCount*/);
3667 expectKeyRepeatOnce(3 /*repeatCount*/);
3668 // Device 2 key up
3669 sendAndConsumeKeyUp(2 /* deviceId */);
3670 mWindow->assertNoEvents();
3671}
3672
3673TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3674 sendAndConsumeKeyDown(1 /* deviceId */);
3675 expectKeyRepeatOnce(1 /*repeatCount*/);
3676 sendAndConsumeKeyDown(2 /* deviceId */);
3677 expectKeyRepeatOnce(1 /*repeatCount*/);
3678 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3679 sendAndConsumeKeyUp(2 /* deviceId */);
3680 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003681 mWindow->assertNoEvents();
3682}
3683
liushenxiang42232912021-05-21 20:24:09 +08003684TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3685 sendAndConsumeKeyDown(DEVICE_ID);
3686 expectKeyRepeatOnce(1 /*repeatCount*/);
3687 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3688 mDispatcher->notifyDeviceReset(&args);
3689 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3690 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3691 mWindow->assertNoEvents();
3692}
3693
Garfield Tan1c7bc862020-01-28 13:24:04 -08003694TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003695 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003696 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3697 InputEvent* repeatEvent = mWindow->consume();
3698 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3699 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3700 IdGenerator::getSource(repeatEvent->getId()));
3701 }
3702}
3703
3704TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003705 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003706
3707 std::unordered_set<int32_t> idSet;
3708 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3709 InputEvent* repeatEvent = mWindow->consume();
3710 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3711 int32_t id = repeatEvent->getId();
3712 EXPECT_EQ(idSet.end(), idSet.find(id));
3713 idSet.insert(id);
3714 }
3715}
3716
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003717/* Test InputDispatcher for MultiDisplay */
3718class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3719public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003720 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003721 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003722
Chris Yea209fde2020-07-22 13:54:51 -07003723 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003724 windowInPrimary =
3725 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003726
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003727 // Set focus window for primary display, but focused display would be second one.
3728 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003729 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003730 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003731 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003732 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003733
Chris Yea209fde2020-07-22 13:54:51 -07003734 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003735 windowInSecondary =
3736 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003737 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003738 // Set focus display to second one.
3739 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3740 // Set focus window for second display.
3741 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003742 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003743 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003744 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003745 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003746 }
3747
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003748 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003749 InputDispatcherTest::TearDown();
3750
Chris Yea209fde2020-07-22 13:54:51 -07003751 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003752 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003753 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003754 windowInSecondary.clear();
3755 }
3756
3757protected:
Chris Yea209fde2020-07-22 13:54:51 -07003758 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003759 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003760 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003761 sp<FakeWindowHandle> windowInSecondary;
3762};
3763
3764TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3765 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003766 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3767 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3768 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003769 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003770 windowInSecondary->assertNoEvents();
3771
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003772 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003773 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3774 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3775 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003776 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003777 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003778}
3779
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003780TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003781 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003782 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3783 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003784 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003785 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003786 windowInSecondary->assertNoEvents();
3787
3788 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003789 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003790 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003791 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003792 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003793
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003794 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003795 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003796
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003797 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003798 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3799 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003800
3801 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003802 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003803 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003804 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003805 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003806 windowInSecondary->assertNoEvents();
3807}
3808
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003809// Test per-display input monitors for motion event.
3810TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003811 FakeMonitorReceiver monitorInPrimary =
3812 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3813 FakeMonitorReceiver monitorInSecondary =
3814 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003815
3816 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003817 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3818 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3819 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003820 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003821 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003822 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003823 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003824
3825 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003826 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3827 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3828 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003829 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003830 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003831 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003832 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003833
3834 // Test inject a non-pointer motion event.
3835 // If specific a display, it will dispatch to the focused window of particular display,
3836 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003837 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3838 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3839 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003840 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003841 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003842 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003843 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003844}
3845
3846// Test per-display input monitors for key event.
3847TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003848 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003849 FakeMonitorReceiver monitorInPrimary =
3850 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3851 FakeMonitorReceiver monitorInSecondary =
3852 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003853
3854 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003855 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3856 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003857 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003858 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003859 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003860 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003861}
3862
Vishnu Nair958da932020-08-21 17:12:37 -07003863TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3864 sp<FakeWindowHandle> secondWindowInPrimary =
3865 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3866 secondWindowInPrimary->setFocusable(true);
3867 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3868 setFocusedWindow(secondWindowInPrimary);
3869 windowInPrimary->consumeFocusEvent(false);
3870 secondWindowInPrimary->consumeFocusEvent(true);
3871
3872 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003873 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3874 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003875 windowInPrimary->assertNoEvents();
3876 windowInSecondary->assertNoEvents();
3877 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3878}
3879
Arthur Hungdfd528e2021-12-08 13:23:04 +00003880TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3881 FakeMonitorReceiver monitorInPrimary =
3882 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3883 FakeMonitorReceiver monitorInSecondary =
3884 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3885
3886 // Test touch down on primary display.
3887 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3888 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3889 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3890 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3891 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3892
3893 // Test touch down on second display.
3894 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3895 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3896 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3897 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3898 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3899
3900 // Trigger cancel touch.
3901 mDispatcher->cancelCurrentTouch();
3902 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3903 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3904 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3905 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3906
3907 // Test inject a move motion event, no window/monitor should receive the event.
3908 ASSERT_EQ(InputEventInjectionResult::FAILED,
3909 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3910 ADISPLAY_ID_DEFAULT, {110, 200}))
3911 << "Inject motion event should return InputEventInjectionResult::FAILED";
3912 windowInPrimary->assertNoEvents();
3913 monitorInPrimary.assertNoEvents();
3914
3915 ASSERT_EQ(InputEventInjectionResult::FAILED,
3916 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3917 SECOND_DISPLAY_ID, {110, 200}))
3918 << "Inject motion event should return InputEventInjectionResult::FAILED";
3919 windowInSecondary->assertNoEvents();
3920 monitorInSecondary.assertNoEvents();
3921}
3922
Jackal Guof9696682018-10-05 12:23:23 +08003923class InputFilterTest : public InputDispatcherTest {
3924protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003925 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3926 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003927 NotifyMotionArgs motionArgs;
3928
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003929 motionArgs =
3930 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003931 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003932 motionArgs =
3933 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003934 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003935 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003936 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003937 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3938 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003939 } else {
3940 mFakePolicy->assertFilterInputEventWasNotCalled();
3941 }
3942 }
3943
3944 void testNotifyKey(bool expectToBeFiltered) {
3945 NotifyKeyArgs keyArgs;
3946
3947 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3948 mDispatcher->notifyKey(&keyArgs);
3949 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3950 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003951 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003952
3953 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003954 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003955 } else {
3956 mFakePolicy->assertFilterInputEventWasNotCalled();
3957 }
3958 }
3959};
3960
3961// Test InputFilter for MotionEvent
3962TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3963 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3964 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3965 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3966
3967 // Enable InputFilter
3968 mDispatcher->setInputFilterEnabled(true);
3969 // Test touch on both primary and second display, and check if both events are filtered.
3970 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3971 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3972
3973 // Disable InputFilter
3974 mDispatcher->setInputFilterEnabled(false);
3975 // Test touch on both primary and second display, and check if both events aren't filtered.
3976 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3977 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3978}
3979
3980// Test InputFilter for KeyEvent
3981TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3982 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3983 testNotifyKey(/*expectToBeFiltered*/ false);
3984
3985 // Enable InputFilter
3986 mDispatcher->setInputFilterEnabled(true);
3987 // Send a key event, and check if it is filtered.
3988 testNotifyKey(/*expectToBeFiltered*/ true);
3989
3990 // Disable InputFilter
3991 mDispatcher->setInputFilterEnabled(false);
3992 // Send a key event, and check if it isn't filtered.
3993 testNotifyKey(/*expectToBeFiltered*/ false);
3994}
3995
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003996// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3997// logical display coordinate space.
3998TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3999 ui::Transform firstDisplayTransform;
4000 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
4001 ui::Transform secondDisplayTransform;
4002 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
4003
4004 std::vector<gui::DisplayInfo> displayInfos(2);
4005 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
4006 displayInfos[0].transform = firstDisplayTransform;
4007 displayInfos[1].displayId = SECOND_DISPLAY_ID;
4008 displayInfos[1].transform = secondDisplayTransform;
4009
4010 mDispatcher->onWindowInfosChanged({}, displayInfos);
4011
4012 // Enable InputFilter
4013 mDispatcher->setInputFilterEnabled(true);
4014
4015 // Ensure the correct transforms are used for the displays.
4016 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
4017 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
4018}
4019
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004020class InputFilterInjectionPolicyTest : public InputDispatcherTest {
4021protected:
4022 virtual void SetUp() override {
4023 InputDispatcherTest::SetUp();
4024
4025 /**
4026 * We don't need to enable input filter to test the injected event policy, but we enabled it
4027 * here to make the tests more realistic, since this policy only matters when inputfilter is
4028 * on.
4029 */
4030 mDispatcher->setInputFilterEnabled(true);
4031
4032 std::shared_ptr<InputApplicationHandle> application =
4033 std::make_shared<FakeApplicationHandle>();
4034 mWindow =
4035 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
4036
4037 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
4038 mWindow->setFocusable(true);
4039 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4040 setFocusedWindow(mWindow);
4041 mWindow->consumeFocusEvent(true);
4042 }
4043
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004044 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4045 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004046 KeyEvent event;
4047
4048 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4049 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4050 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4051 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4052 const int32_t additionalPolicyFlags =
4053 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4054 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4055 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
4056 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4057 policyFlags | additionalPolicyFlags));
4058
4059 InputEvent* received = mWindow->consume();
4060 ASSERT_NE(nullptr, received);
4061 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004062 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4063 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4064 ASSERT_EQ(flags, keyEvent.getFlags());
4065 }
4066
4067 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4068 int32_t flags) {
4069 MotionEvent event;
4070 PointerProperties pointerProperties[1];
4071 PointerCoords pointerCoords[1];
4072 pointerProperties[0].clear();
4073 pointerProperties[0].id = 0;
4074 pointerCoords[0].clear();
4075 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4076 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4077
4078 ui::Transform identityTransform;
4079 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4080 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4081 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4082 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4083 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004084 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004085 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004086 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4087
4088 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4089 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4090 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
4091 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4092 policyFlags | additionalPolicyFlags));
4093
4094 InputEvent* received = mWindow->consume();
4095 ASSERT_NE(nullptr, received);
4096 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4097 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4098 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4099 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004100 }
4101
4102private:
4103 sp<FakeWindowHandle> mWindow;
4104};
4105
4106TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004107 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4108 // filter. Without it, the event will no different from a regularly injected event, and the
4109 // injected device id will be overwritten.
4110 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4111 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004112}
4113
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004114TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004115 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004116 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4117 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4118}
4119
4120TEST_F(InputFilterInjectionPolicyTest,
4121 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4122 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4123 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4124 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004125}
4126
4127TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4128 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004129 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004130}
4131
chaviwfd6d3512019-03-25 13:23:49 -07004132class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004133 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004134 InputDispatcherTest::SetUp();
4135
Chris Yea209fde2020-07-22 13:54:51 -07004136 std::shared_ptr<FakeApplicationHandle> application =
4137 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004138 mUnfocusedWindow =
4139 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004140 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004141
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004142 mFocusedWindow =
4143 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4144 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004145
4146 // Set focused application.
4147 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004148 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004149
4150 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004151 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004152 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004153 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004154 }
4155
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004156 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004157 InputDispatcherTest::TearDown();
4158
4159 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004160 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004161 }
4162
4163protected:
4164 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004165 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004166 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004167};
4168
4169// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4170// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4171// the onPointerDownOutsideFocus callback.
4172TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004173 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004174 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4175 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004176 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004177 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004178
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004179 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004180 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4181}
4182
4183// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4184// DOWN on the window that doesn't have focus. Ensure no window received the
4185// onPointerDownOutsideFocus callback.
4186TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004187 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004188 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004189 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004190 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004191
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004192 ASSERT_TRUE(mDispatcher->waitForIdle());
4193 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004194}
4195
4196// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4197// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4198TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004199 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4200 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004201 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004202 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004203
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004204 ASSERT_TRUE(mDispatcher->waitForIdle());
4205 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004206}
4207
4208// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4209// DOWN on the window that already has focus. Ensure no window received the
4210// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004211TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004212 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004213 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004214 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004215 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004216 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004217
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004218 ASSERT_TRUE(mDispatcher->waitForIdle());
4219 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004220}
4221
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004222// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4223// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4224TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4225 const MotionEvent event =
4226 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4227 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4228 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4229 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4230 .build();
4231 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4232 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4233 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4234
4235 ASSERT_TRUE(mDispatcher->waitForIdle());
4236 mFakePolicy->assertOnPointerDownWasNotCalled();
4237 // Ensure that the unfocused window did not receive any FOCUS events.
4238 mUnfocusedWindow->assertNoEvents();
4239}
4240
chaviwaf87b3e2019-10-01 16:59:28 -07004241// These tests ensures we can send touch events to a single client when there are multiple input
4242// windows that point to the same client token.
4243class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4244 virtual void SetUp() override {
4245 InputDispatcherTest::SetUp();
4246
Chris Yea209fde2020-07-22 13:54:51 -07004247 std::shared_ptr<FakeApplicationHandle> application =
4248 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004249 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4250 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004251 mWindow1->setFrame(Rect(0, 0, 100, 100));
4252
4253 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4254 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004255 mWindow2->setFrame(Rect(100, 100, 200, 200));
4256
Arthur Hung72d8dc32020-03-28 00:48:39 +00004257 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004258 }
4259
4260protected:
4261 sp<FakeWindowHandle> mWindow1;
4262 sp<FakeWindowHandle> mWindow2;
4263
4264 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004265 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004266 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4267 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004268 }
4269
4270 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4271 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004272 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004273 InputEvent* event = window->consume();
4274
4275 ASSERT_NE(nullptr, event) << name.c_str()
4276 << ": consumer should have returned non-NULL event.";
4277
4278 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4279 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4280 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4281
4282 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004283 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004284
4285 for (size_t i = 0; i < points.size(); i++) {
4286 float expectedX = points[i].x;
4287 float expectedY = points[i].y;
4288
4289 EXPECT_EQ(expectedX, motionEvent.getX(i))
4290 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4291 << ", got " << motionEvent.getX(i);
4292 EXPECT_EQ(expectedY, motionEvent.getY(i))
4293 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4294 << ", got " << motionEvent.getY(i);
4295 }
4296 }
chaviw9eaa22c2020-07-01 16:21:27 -07004297
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004298 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004299 std::vector<PointF> expectedPoints) {
4300 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4301 ADISPLAY_ID_DEFAULT, touchedPoints);
4302 mDispatcher->notifyMotion(&motionArgs);
4303
4304 // Always consume from window1 since it's the window that has the InputReceiver
4305 consumeMotionEvent(mWindow1, action, expectedPoints);
4306 }
chaviwaf87b3e2019-10-01 16:59:28 -07004307};
4308
4309TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4310 // Touch Window 1
4311 PointF touchedPoint = {10, 10};
4312 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004313 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004314
4315 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004316 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004317
4318 // Touch Window 2
4319 touchedPoint = {150, 150};
4320 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004321 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004322}
4323
chaviw9eaa22c2020-07-01 16:21:27 -07004324TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4325 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004326 mWindow2->setWindowScale(0.5f, 0.5f);
4327
4328 // Touch Window 1
4329 PointF touchedPoint = {10, 10};
4330 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004331 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004332 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004333 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004334
4335 // Touch Window 2
4336 touchedPoint = {150, 150};
4337 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004338 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4339 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004340
chaviw9eaa22c2020-07-01 16:21:27 -07004341 // Update the transform so rotation is set
4342 mWindow2->setWindowTransform(0, -1, 1, 0);
4343 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4344 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004345}
4346
chaviw9eaa22c2020-07-01 16:21:27 -07004347TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004348 mWindow2->setWindowScale(0.5f, 0.5f);
4349
4350 // Touch Window 1
4351 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4352 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004353 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004354
4355 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004356 touchedPoints.push_back(PointF{150, 150});
4357 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004358 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004359
chaviw9eaa22c2020-07-01 16:21:27 -07004360 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004361 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004362 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004363
chaviw9eaa22c2020-07-01 16:21:27 -07004364 // Update the transform so rotation is set for Window 2
4365 mWindow2->setWindowTransform(0, -1, 1, 0);
4366 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004367 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004368}
4369
chaviw9eaa22c2020-07-01 16:21:27 -07004370TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004371 mWindow2->setWindowScale(0.5f, 0.5f);
4372
4373 // Touch Window 1
4374 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4375 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004376 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004377
4378 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004379 touchedPoints.push_back(PointF{150, 150});
4380 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004381
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004382 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004383
4384 // Move both windows
4385 touchedPoints = {{20, 20}, {175, 175}};
4386 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4387 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4388
chaviw9eaa22c2020-07-01 16:21:27 -07004389 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004390
chaviw9eaa22c2020-07-01 16:21:27 -07004391 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004392 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004393 expectedPoints.pop_back();
4394
4395 // Touch Window 2
4396 mWindow2->setWindowTransform(0, -1, 1, 0);
4397 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004398 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004399
4400 // Move both windows
4401 touchedPoints = {{20, 20}, {175, 175}};
4402 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4403 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4404
4405 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004406}
4407
4408TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4409 mWindow1->setWindowScale(0.5f, 0.5f);
4410
4411 // Touch Window 1
4412 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4413 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004414 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004415
4416 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004417 touchedPoints.push_back(PointF{150, 150});
4418 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004419
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004420 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004421
4422 // Move both windows
4423 touchedPoints = {{20, 20}, {175, 175}};
4424 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4425 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4426
chaviw9eaa22c2020-07-01 16:21:27 -07004427 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004428}
4429
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004430class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4431 virtual void SetUp() override {
4432 InputDispatcherTest::SetUp();
4433
Chris Yea209fde2020-07-22 13:54:51 -07004434 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004435 mApplication->setDispatchingTimeout(20ms);
4436 mWindow =
4437 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4438 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004439 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004440 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004441
4442 // Set focused application.
4443 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4444
4445 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004446 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004447 mWindow->consumeFocusEvent(true);
4448 }
4449
4450 virtual void TearDown() override {
4451 InputDispatcherTest::TearDown();
4452 mWindow.clear();
4453 }
4454
4455protected:
Chris Yea209fde2020-07-22 13:54:51 -07004456 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004457 sp<FakeWindowHandle> mWindow;
4458 static constexpr PointF WINDOW_LOCATION = {20, 20};
4459
4460 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004461 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004462 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4463 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004464 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004465 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4466 WINDOW_LOCATION));
4467 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004468
4469 sp<FakeWindowHandle> addSpyWindow() {
4470 sp<FakeWindowHandle> spy =
4471 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4472 spy->setTrustedOverlay(true);
4473 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004474 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004475 spy->setDispatchingTimeout(30ms);
4476 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4477 return spy;
4478 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004479};
4480
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004481// Send a tap and respond, which should not cause an ANR.
4482TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4483 tapOnWindow();
4484 mWindow->consumeMotionDown();
4485 mWindow->consumeMotionUp();
4486 ASSERT_TRUE(mDispatcher->waitForIdle());
4487 mFakePolicy->assertNotifyAnrWasNotCalled();
4488}
4489
4490// Send a regular key and respond, which should not cause an ANR.
4491TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004492 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004493 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4494 ASSERT_TRUE(mDispatcher->waitForIdle());
4495 mFakePolicy->assertNotifyAnrWasNotCalled();
4496}
4497
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004498TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4499 mWindow->setFocusable(false);
4500 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4501 mWindow->consumeFocusEvent(false);
4502
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004503 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004504 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004505 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4506 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004507 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004508 // Key will not go to window because we have no focused window.
4509 // The 'no focused window' ANR timer should start instead.
4510
4511 // Now, the focused application goes away.
4512 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4513 // The key should get dropped and there should be no ANR.
4514
4515 ASSERT_TRUE(mDispatcher->waitForIdle());
4516 mFakePolicy->assertNotifyAnrWasNotCalled();
4517}
4518
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004519// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004520// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4521// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004522TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004523 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004524 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4525 WINDOW_LOCATION));
4526
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004527 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4528 ASSERT_TRUE(sequenceNum);
4529 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004530 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004531
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004532 mWindow->finishEvent(*sequenceNum);
4533 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4534 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004535 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004536 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004537}
4538
4539// Send a key to the app and have the app not respond right away.
4540TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4541 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004542 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004543 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4544 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004545 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004546 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004547 ASSERT_TRUE(mDispatcher->waitForIdle());
4548}
4549
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004550// We have a focused application, but no focused window
4551TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004552 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004553 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4554 mWindow->consumeFocusEvent(false);
4555
4556 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004557 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004558 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4559 WINDOW_LOCATION));
4560 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4561 mDispatcher->waitForIdle();
4562 mFakePolicy->assertNotifyAnrWasNotCalled();
4563
4564 // Once a focused event arrives, we get an ANR for this application
4565 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4566 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004567 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004568 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004569 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004570 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004571 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004572 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004573 ASSERT_TRUE(mDispatcher->waitForIdle());
4574}
4575
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004576/**
4577 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4578 * there will not be an ANR.
4579 */
4580TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4581 mWindow->setFocusable(false);
4582 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4583 mWindow->consumeFocusEvent(false);
4584
4585 KeyEvent event;
4586 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4587 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4588
4589 // Define a valid key down event that is stale (too old).
4590 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4591 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4592 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4593
4594 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4595
4596 InputEventInjectionResult result =
4597 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
4598 InputEventInjectionSync::WAIT_FOR_RESULT,
4599 INJECT_EVENT_TIMEOUT, policyFlags);
4600 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4601 << "Injection should fail because the event is stale";
4602
4603 ASSERT_TRUE(mDispatcher->waitForIdle());
4604 mFakePolicy->assertNotifyAnrWasNotCalled();
4605 mWindow->assertNoEvents();
4606}
4607
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004608// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004609// Make sure that we don't notify policy twice about the same ANR.
4610TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004611 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004612 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4613 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004614
4615 // Once a focused event arrives, we get an ANR for this application
4616 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4617 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004618 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004619 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004620 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004621 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004622 const std::chrono::duration appTimeout =
4623 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004624 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004625
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004626 std::this_thread::sleep_for(appTimeout);
4627 // ANR should not be raised again. It is up to policy to do that if it desires.
4628 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004629
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004630 // If we now get a focused window, the ANR should stop, but the policy handles that via
4631 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004632 ASSERT_TRUE(mDispatcher->waitForIdle());
4633}
4634
4635// We have a focused application, but no focused window
4636TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004637 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004638 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4639 mWindow->consumeFocusEvent(false);
4640
4641 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004642 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004643 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004644 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4645 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004646
4647 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004648 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004649
4650 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004651 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004652 ASSERT_TRUE(mDispatcher->waitForIdle());
4653 mWindow->assertNoEvents();
4654}
4655
4656/**
4657 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4658 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4659 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4660 * the ANR mechanism should still work.
4661 *
4662 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4663 * DOWN event, while not responding on the second one.
4664 */
4665TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4666 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4667 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4668 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4669 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4670 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004671 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004672
4673 // Now send ACTION_UP, with identical timestamp
4674 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4675 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4676 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4677 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004678 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004679
4680 // We have now sent down and up. Let's consume first event and then ANR on the second.
4681 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4682 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004683 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004684}
4685
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004686// A spy window can receive an ANR
4687TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4688 sp<FakeWindowHandle> spy = addSpyWindow();
4689
4690 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4691 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4692 WINDOW_LOCATION));
4693 mWindow->consumeMotionDown();
4694
4695 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4696 ASSERT_TRUE(sequenceNum);
4697 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004698 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004699
4700 spy->finishEvent(*sequenceNum);
4701 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4702 0 /*flags*/);
4703 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004704 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004705}
4706
4707// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004708// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004709TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4710 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004711
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004712 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4713 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004714 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004715 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004716
4717 // Stuck on the ACTION_UP
4718 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004719 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004720
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004721 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004722 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004723 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4724 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004725
4726 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4727 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004728 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004729 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004730 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004731}
4732
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004733// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004734// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004735TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4736 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004737
4738 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004739 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4740 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004741
4742 mWindow->consumeMotionDown();
4743 // Stuck on the ACTION_UP
4744 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004745 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004746
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004747 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004748 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004749 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4750 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004751
4752 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4753 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004754 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004755 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004756 spy->assertNoEvents();
4757}
4758
4759TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4760 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4761
4762 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4763
4764 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4765 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4766 WINDOW_LOCATION));
4767
4768 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4769 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4770 ASSERT_TRUE(consumeSeq);
4771
Prabir Pradhanedd96402022-02-15 01:46:16 -08004772 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004773
4774 monitor.finishEvent(*consumeSeq);
4775 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4776
4777 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004778 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004779}
4780
4781// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4782// process events, you don't get an anr. When the window later becomes unresponsive again, you
4783// get an ANR again.
4784// 1. tap -> block on ACTION_UP -> receive ANR
4785// 2. consume all pending events (= queue becomes healthy again)
4786// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4787TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4788 tapOnWindow();
4789
4790 mWindow->consumeMotionDown();
4791 // Block on ACTION_UP
4792 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004793 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004794 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4795 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004796 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004797 mWindow->assertNoEvents();
4798
4799 tapOnWindow();
4800 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004801 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004802 mWindow->consumeMotionUp();
4803
4804 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004805 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004806 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004807 mWindow->assertNoEvents();
4808}
4809
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004810// If a connection remains unresponsive for a while, make sure policy is only notified once about
4811// it.
4812TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004813 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004814 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4815 WINDOW_LOCATION));
4816
4817 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004818 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004819 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004820 // 'notifyConnectionUnresponsive' should only be called once per connection
4821 mFakePolicy->assertNotifyAnrWasNotCalled();
4822 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004823 mWindow->consumeMotionDown();
4824 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4825 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4826 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004827 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004828 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004829 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004830}
4831
4832/**
4833 * If a window is processing a motion event, and then a key event comes in, the key event should
4834 * not to to the focused window until the motion is processed.
4835 *
4836 * Warning!!!
4837 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4838 * and the injection timeout that we specify when injecting the key.
4839 * We must have the injection timeout (10ms) be smaller than
4840 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4841 *
4842 * If that value changes, this test should also change.
4843 */
4844TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4845 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4846 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4847
4848 tapOnWindow();
4849 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4850 ASSERT_TRUE(downSequenceNum);
4851 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4852 ASSERT_TRUE(upSequenceNum);
4853 // Don't finish the events yet, and send a key
4854 // Injection will "succeed" because we will eventually give up and send the key to the focused
4855 // window even if motions are still being processed. But because the injection timeout is short,
4856 // we will receive INJECTION_TIMED_OUT as the result.
4857
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004858 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004859 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004860 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4861 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004862 // Key will not be sent to the window, yet, because the window is still processing events
4863 // and the key remains pending, waiting for the touch events to be processed
4864 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4865 ASSERT_FALSE(keySequenceNum);
4866
4867 std::this_thread::sleep_for(500ms);
4868 // if we wait long enough though, dispatcher will give up, and still send the key
4869 // to the focused window, even though we have not yet finished the motion event
4870 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4871 mWindow->finishEvent(*downSequenceNum);
4872 mWindow->finishEvent(*upSequenceNum);
4873}
4874
4875/**
4876 * If a window is processing a motion event, and then a key event comes in, the key event should
4877 * not go to the focused window until the motion is processed.
4878 * If then a new motion comes in, then the pending key event should be going to the currently
4879 * focused window right away.
4880 */
4881TEST_F(InputDispatcherSingleWindowAnr,
4882 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4883 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4884 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4885
4886 tapOnWindow();
4887 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4888 ASSERT_TRUE(downSequenceNum);
4889 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4890 ASSERT_TRUE(upSequenceNum);
4891 // Don't finish the events yet, and send a key
4892 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004893 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004894 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004895 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004896 // At this point, key is still pending, and should not be sent to the application yet.
4897 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4898 ASSERT_FALSE(keySequenceNum);
4899
4900 // Now tap down again. It should cause the pending key to go to the focused window right away.
4901 tapOnWindow();
4902 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4903 // the other events yet. We can finish events in any order.
4904 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4905 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4906 mWindow->consumeMotionDown();
4907 mWindow->consumeMotionUp();
4908 mWindow->assertNoEvents();
4909}
4910
4911class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4912 virtual void SetUp() override {
4913 InputDispatcherTest::SetUp();
4914
Chris Yea209fde2020-07-22 13:54:51 -07004915 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004916 mApplication->setDispatchingTimeout(10ms);
4917 mUnfocusedWindow =
4918 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4919 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004920 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004921 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004922
4923 mFocusedWindow =
4924 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004925 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004926 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004927
4928 // Set focused application.
4929 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004930 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004931
4932 // Expect one focus window exist in display.
4933 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004934 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004935 mFocusedWindow->consumeFocusEvent(true);
4936 }
4937
4938 virtual void TearDown() override {
4939 InputDispatcherTest::TearDown();
4940
4941 mUnfocusedWindow.clear();
4942 mFocusedWindow.clear();
4943 }
4944
4945protected:
Chris Yea209fde2020-07-22 13:54:51 -07004946 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004947 sp<FakeWindowHandle> mUnfocusedWindow;
4948 sp<FakeWindowHandle> mFocusedWindow;
4949 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4950 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4951 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4952
4953 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4954
4955 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4956
4957private:
4958 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004959 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004960 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4961 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004962 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004963 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4964 location));
4965 }
4966};
4967
4968// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4969// should be ANR'd first.
4970TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004971 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004972 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4973 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004974 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004975 mFocusedWindow->consumeMotionDown();
4976 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4977 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4978 // We consumed all events, so no ANR
4979 ASSERT_TRUE(mDispatcher->waitForIdle());
4980 mFakePolicy->assertNotifyAnrWasNotCalled();
4981
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004982 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004983 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4984 FOCUSED_WINDOW_LOCATION));
4985 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4986 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004987
4988 const std::chrono::duration timeout =
4989 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004990 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004991 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4992 // sequence to make it consistent
4993 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004994 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004995 mFocusedWindow->consumeMotionDown();
4996 // This cancel is generated because the connection was unresponsive
4997 mFocusedWindow->consumeMotionCancel();
4998 mFocusedWindow->assertNoEvents();
4999 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005000 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005001 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5002 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005003 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005004}
5005
5006// If we have 2 windows with identical timeouts that are both unresponsive,
5007// it doesn't matter which order they should have ANR.
5008// But we should receive ANR for both.
5009TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
5010 // Set the timeout for unfocused window to match the focused window
5011 mUnfocusedWindow->setDispatchingTimeout(10ms);
5012 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5013
5014 tapOnFocusedWindow();
5015 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08005016 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
5017 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
5018 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005019
5020 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005021 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
5022 mFocusedWindow->getToken() == anrConnectionToken2);
5023 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
5024 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005025
5026 ASSERT_TRUE(mDispatcher->waitForIdle());
5027 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005028
5029 mFocusedWindow->consumeMotionDown();
5030 mFocusedWindow->consumeMotionUp();
5031 mUnfocusedWindow->consumeMotionOutside();
5032
Prabir Pradhanedd96402022-02-15 01:46:16 -08005033 sp<IBinder> responsiveToken1, responsiveToken2;
5034 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
5035 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005036
5037 // Both applications should be marked as responsive, in any order
5038 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
5039 mFocusedWindow->getToken() == responsiveToken2);
5040 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
5041 mUnfocusedWindow->getToken() == responsiveToken2);
5042 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005043}
5044
5045// If a window is already not responding, the second tap on the same window should be ignored.
5046// We should also log an error to account for the dropped event (not tested here).
5047// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
5048TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
5049 tapOnFocusedWindow();
5050 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5051 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5052 // Receive the events, but don't respond
5053 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
5054 ASSERT_TRUE(downEventSequenceNum);
5055 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
5056 ASSERT_TRUE(upEventSequenceNum);
5057 const std::chrono::duration timeout =
5058 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005059 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005060
5061 // Tap once again
5062 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005063 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005064 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5065 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005066 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005067 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5068 FOCUSED_WINDOW_LOCATION));
5069 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5070 // valid touch target
5071 mUnfocusedWindow->assertNoEvents();
5072
5073 // Consume the first tap
5074 mFocusedWindow->finishEvent(*downEventSequenceNum);
5075 mFocusedWindow->finishEvent(*upEventSequenceNum);
5076 ASSERT_TRUE(mDispatcher->waitForIdle());
5077 // The second tap did not go to the focused window
5078 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005079 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005080 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5081 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005082 mFakePolicy->assertNotifyAnrWasNotCalled();
5083}
5084
5085// If you tap outside of all windows, there will not be ANR
5086TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005087 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005088 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5089 LOCATION_OUTSIDE_ALL_WINDOWS));
5090 ASSERT_TRUE(mDispatcher->waitForIdle());
5091 mFakePolicy->assertNotifyAnrWasNotCalled();
5092}
5093
5094// Since the focused window is paused, tapping on it should not produce any events
5095TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5096 mFocusedWindow->setPaused(true);
5097 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5098
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005099 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005100 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5101 FOCUSED_WINDOW_LOCATION));
5102
5103 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5104 ASSERT_TRUE(mDispatcher->waitForIdle());
5105 // Should not ANR because the window is paused, and touches shouldn't go to it
5106 mFakePolicy->assertNotifyAnrWasNotCalled();
5107
5108 mFocusedWindow->assertNoEvents();
5109 mUnfocusedWindow->assertNoEvents();
5110}
5111
5112/**
5113 * If a window is processing a motion event, and then a key event comes in, the key event should
5114 * not to to the focused window until the motion is processed.
5115 * If a different window becomes focused at this time, the key should go to that window instead.
5116 *
5117 * Warning!!!
5118 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5119 * and the injection timeout that we specify when injecting the key.
5120 * We must have the injection timeout (10ms) be smaller than
5121 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5122 *
5123 * If that value changes, this test should also change.
5124 */
5125TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5126 // Set a long ANR timeout to prevent it from triggering
5127 mFocusedWindow->setDispatchingTimeout(2s);
5128 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5129
5130 tapOnUnfocusedWindow();
5131 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5132 ASSERT_TRUE(downSequenceNum);
5133 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5134 ASSERT_TRUE(upSequenceNum);
5135 // Don't finish the events yet, and send a key
5136 // Injection will succeed because we will eventually give up and send the key to the focused
5137 // window even if motions are still being processed.
5138
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005139 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005140 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005141 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5142 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005143 // Key will not be sent to the window, yet, because the window is still processing events
5144 // and the key remains pending, waiting for the touch events to be processed
5145 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5146 ASSERT_FALSE(keySequenceNum);
5147
5148 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005149 mFocusedWindow->setFocusable(false);
5150 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005151 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005152 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005153
5154 // Focus events should precede the key events
5155 mUnfocusedWindow->consumeFocusEvent(true);
5156 mFocusedWindow->consumeFocusEvent(false);
5157
5158 // Finish the tap events, which should unblock dispatcher
5159 mUnfocusedWindow->finishEvent(*downSequenceNum);
5160 mUnfocusedWindow->finishEvent(*upSequenceNum);
5161
5162 // Now that all queues are cleared and no backlog in the connections, the key event
5163 // can finally go to the newly focused "mUnfocusedWindow".
5164 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5165 mFocusedWindow->assertNoEvents();
5166 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005167 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005168}
5169
5170// When the touch stream is split across 2 windows, and one of them does not respond,
5171// then ANR should be raised and the touch should be canceled for the unresponsive window.
5172// The other window should not be affected by that.
5173TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5174 // Touch Window 1
5175 NotifyMotionArgs motionArgs =
5176 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5177 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5178 mDispatcher->notifyMotion(&motionArgs);
5179 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5180 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5181
5182 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005183 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5184 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005185 mDispatcher->notifyMotion(&motionArgs);
5186
5187 const std::chrono::duration timeout =
5188 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005189 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005190
5191 mUnfocusedWindow->consumeMotionDown();
5192 mFocusedWindow->consumeMotionDown();
5193 // Focused window may or may not receive ACTION_MOVE
5194 // But it should definitely receive ACTION_CANCEL due to the ANR
5195 InputEvent* event;
5196 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5197 ASSERT_TRUE(moveOrCancelSequenceNum);
5198 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5199 ASSERT_NE(nullptr, event);
5200 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5201 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5202 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5203 mFocusedWindow->consumeMotionCancel();
5204 } else {
5205 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5206 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005207 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005208 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5209 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005210
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005211 mUnfocusedWindow->assertNoEvents();
5212 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005213 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005214}
5215
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005216/**
5217 * If we have no focused window, and a key comes in, we start the ANR timer.
5218 * The focused application should add a focused window before the timer runs out to prevent ANR.
5219 *
5220 * If the user touches another application during this time, the key should be dropped.
5221 * Next, if a new focused window comes in, without toggling the focused application,
5222 * then no ANR should occur.
5223 *
5224 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5225 * but in some cases the policy may not update the focused application.
5226 */
5227TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5228 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5229 std::make_shared<FakeApplicationHandle>();
5230 focusedApplication->setDispatchingTimeout(60ms);
5231 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5232 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5233 mFocusedWindow->setFocusable(false);
5234
5235 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5236 mFocusedWindow->consumeFocusEvent(false);
5237
5238 // Send a key. The ANR timer should start because there is no focused window.
5239 // 'focusedApplication' will get blamed if this timer completes.
5240 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005241 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005242 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005243 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5244 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005245 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005246
5247 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5248 // then the injected touches won't cause the focused event to get dropped.
5249 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5250 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5251 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5252 // For this test, it means that the key would get delivered to the window once it becomes
5253 // focused.
5254 std::this_thread::sleep_for(10ms);
5255
5256 // Touch unfocused window. This should force the pending key to get dropped.
5257 NotifyMotionArgs motionArgs =
5258 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5259 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5260 mDispatcher->notifyMotion(&motionArgs);
5261
5262 // We do not consume the motion right away, because that would require dispatcher to first
5263 // process (== drop) the key event, and by that time, ANR will be raised.
5264 // Set the focused window first.
5265 mFocusedWindow->setFocusable(true);
5266 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5267 setFocusedWindow(mFocusedWindow);
5268 mFocusedWindow->consumeFocusEvent(true);
5269 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5270 // to another application. This could be a bug / behaviour in the policy.
5271
5272 mUnfocusedWindow->consumeMotionDown();
5273
5274 ASSERT_TRUE(mDispatcher->waitForIdle());
5275 // Should not ANR because we actually have a focused window. It was just added too slowly.
5276 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5277}
5278
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005279// These tests ensure we cannot send touch events to a window that's positioned behind a window
5280// that has feature NO_INPUT_CHANNEL.
5281// Layout:
5282// Top (closest to user)
5283// mNoInputWindow (above all windows)
5284// mBottomWindow
5285// Bottom (furthest from user)
5286class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5287 virtual void SetUp() override {
5288 InputDispatcherTest::SetUp();
5289
5290 mApplication = std::make_shared<FakeApplicationHandle>();
5291 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5292 "Window without input channel", ADISPLAY_ID_DEFAULT,
5293 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5294
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005295 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005296 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5297 // It's perfectly valid for this window to not have an associated input channel
5298
5299 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5300 ADISPLAY_ID_DEFAULT);
5301 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5302
5303 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5304 }
5305
5306protected:
5307 std::shared_ptr<FakeApplicationHandle> mApplication;
5308 sp<FakeWindowHandle> mNoInputWindow;
5309 sp<FakeWindowHandle> mBottomWindow;
5310};
5311
5312TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5313 PointF touchedPoint = {10, 10};
5314
5315 NotifyMotionArgs motionArgs =
5316 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5317 ADISPLAY_ID_DEFAULT, {touchedPoint});
5318 mDispatcher->notifyMotion(&motionArgs);
5319
5320 mNoInputWindow->assertNoEvents();
5321 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5322 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5323 // and therefore should prevent mBottomWindow from receiving touches
5324 mBottomWindow->assertNoEvents();
5325}
5326
5327/**
5328 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5329 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5330 */
5331TEST_F(InputDispatcherMultiWindowOcclusionTests,
5332 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5333 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5334 "Window with input channel and NO_INPUT_CHANNEL",
5335 ADISPLAY_ID_DEFAULT);
5336
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005337 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005338 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5339 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5340
5341 PointF touchedPoint = {10, 10};
5342
5343 NotifyMotionArgs motionArgs =
5344 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5345 ADISPLAY_ID_DEFAULT, {touchedPoint});
5346 mDispatcher->notifyMotion(&motionArgs);
5347
5348 mNoInputWindow->assertNoEvents();
5349 mBottomWindow->assertNoEvents();
5350}
5351
Vishnu Nair958da932020-08-21 17:12:37 -07005352class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5353protected:
5354 std::shared_ptr<FakeApplicationHandle> mApp;
5355 sp<FakeWindowHandle> mWindow;
5356 sp<FakeWindowHandle> mMirror;
5357
5358 virtual void SetUp() override {
5359 InputDispatcherTest::SetUp();
5360 mApp = std::make_shared<FakeApplicationHandle>();
5361 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5362 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5363 mWindow->getToken());
5364 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5365 mWindow->setFocusable(true);
5366 mMirror->setFocusable(true);
5367 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5368 }
5369};
5370
5371TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5372 // Request focus on a mirrored window
5373 setFocusedWindow(mMirror);
5374
5375 // window gets focused
5376 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005377 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5378 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005379 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5380}
5381
5382// A focused & mirrored window remains focused only if the window and its mirror are both
5383// focusable.
5384TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5385 setFocusedWindow(mMirror);
5386
5387 // window gets focused
5388 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005389 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5390 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005391 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005392 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5393 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005394 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5395
5396 mMirror->setFocusable(false);
5397 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5398
5399 // window loses focus since one of the windows associated with the token in not focusable
5400 mWindow->consumeFocusEvent(false);
5401
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005402 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5403 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005404 mWindow->assertNoEvents();
5405}
5406
5407// A focused & mirrored window remains focused until the window and its mirror both become
5408// invisible.
5409TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5410 setFocusedWindow(mMirror);
5411
5412 // window gets focused
5413 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005414 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5415 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005416 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005417 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5418 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005419 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5420
5421 mMirror->setVisible(false);
5422 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5423
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005424 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5425 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005426 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005427 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5428 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005429 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5430
5431 mWindow->setVisible(false);
5432 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5433
5434 // window loses focus only after all windows associated with the token become invisible.
5435 mWindow->consumeFocusEvent(false);
5436
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005437 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5438 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005439 mWindow->assertNoEvents();
5440}
5441
5442// A focused & mirrored window remains focused until both windows are removed.
5443TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5444 setFocusedWindow(mMirror);
5445
5446 // window gets focused
5447 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005448 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5449 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005450 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005451 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5452 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005453 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5454
5455 // single window is removed but the window token remains focused
5456 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5457
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005458 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5459 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005460 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005461 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5462 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005463 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5464
5465 // Both windows are removed
5466 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5467 mWindow->consumeFocusEvent(false);
5468
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005469 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5470 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005471 mWindow->assertNoEvents();
5472}
5473
5474// Focus request can be pending until one window becomes visible.
5475TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5476 // Request focus on an invisible mirror.
5477 mWindow->setVisible(false);
5478 mMirror->setVisible(false);
5479 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5480 setFocusedWindow(mMirror);
5481
5482 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005483 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005484 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005485 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005486
5487 mMirror->setVisible(true);
5488 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5489
5490 // window gets focused
5491 mWindow->consumeFocusEvent(true);
5492 // window gets the pending key event
5493 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5494}
Prabir Pradhan99987712020-11-10 18:43:05 -08005495
5496class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5497protected:
5498 std::shared_ptr<FakeApplicationHandle> mApp;
5499 sp<FakeWindowHandle> mWindow;
5500 sp<FakeWindowHandle> mSecondWindow;
5501
5502 void SetUp() override {
5503 InputDispatcherTest::SetUp();
5504 mApp = std::make_shared<FakeApplicationHandle>();
5505 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5506 mWindow->setFocusable(true);
5507 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5508 mSecondWindow->setFocusable(true);
5509
5510 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5511 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5512
5513 setFocusedWindow(mWindow);
5514 mWindow->consumeFocusEvent(true);
5515 }
5516
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005517 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5518 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005519 mDispatcher->notifyPointerCaptureChanged(&args);
5520 }
5521
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005522 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5523 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005524 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005525 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5526 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005527 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005528 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005529 }
5530};
5531
5532TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5533 // Ensure that capture cannot be obtained for unfocused windows.
5534 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5535 mFakePolicy->assertSetPointerCaptureNotCalled();
5536 mSecondWindow->assertNoEvents();
5537
5538 // Ensure that capture can be enabled from the focus window.
5539 requestAndVerifyPointerCapture(mWindow, true);
5540
5541 // Ensure that capture cannot be disabled from a window that does not have capture.
5542 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5543 mFakePolicy->assertSetPointerCaptureNotCalled();
5544
5545 // Ensure that capture can be disabled from the window with capture.
5546 requestAndVerifyPointerCapture(mWindow, false);
5547}
5548
5549TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005550 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005551
5552 setFocusedWindow(mSecondWindow);
5553
5554 // Ensure that the capture disabled event was sent first.
5555 mWindow->consumeCaptureEvent(false);
5556 mWindow->consumeFocusEvent(false);
5557 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005558 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005559
5560 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005561 notifyPointerCaptureChanged({});
5562 notifyPointerCaptureChanged(request);
5563 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005564 mWindow->assertNoEvents();
5565 mSecondWindow->assertNoEvents();
5566 mFakePolicy->assertSetPointerCaptureNotCalled();
5567}
5568
5569TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005570 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005571
5572 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005573 notifyPointerCaptureChanged({});
5574 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005575
5576 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005577 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005578 mWindow->consumeCaptureEvent(false);
5579 mWindow->assertNoEvents();
5580}
5581
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005582TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5583 requestAndVerifyPointerCapture(mWindow, true);
5584
5585 // The first window loses focus.
5586 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005587 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005588 mWindow->consumeCaptureEvent(false);
5589
5590 // Request Pointer Capture from the second window before the notification from InputReader
5591 // arrives.
5592 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005593 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005594
5595 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005596 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005597
5598 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005599 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005600
5601 mSecondWindow->consumeFocusEvent(true);
5602 mSecondWindow->consumeCaptureEvent(true);
5603}
5604
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005605TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5606 // App repeatedly enables and disables capture.
5607 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5608 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5609 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5610 mFakePolicy->assertSetPointerCaptureCalled(false);
5611 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5612 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5613
5614 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5615 // first request is now stale, this should do nothing.
5616 notifyPointerCaptureChanged(firstRequest);
5617 mWindow->assertNoEvents();
5618
5619 // InputReader notifies that the second request was enabled.
5620 notifyPointerCaptureChanged(secondRequest);
5621 mWindow->consumeCaptureEvent(true);
5622}
5623
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005624class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5625protected:
5626 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005627
5628 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5629 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5630
5631 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5632 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5633
5634 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5635 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5636 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5637 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5638 MAXIMUM_OBSCURING_OPACITY);
5639
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005640 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005641 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005642 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005643
5644 sp<FakeWindowHandle> mTouchWindow;
5645
5646 virtual void SetUp() override {
5647 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005648 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005649 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5650 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5651 }
5652
5653 virtual void TearDown() override {
5654 InputDispatcherTest::TearDown();
5655 mTouchWindow.clear();
5656 }
5657
chaviw3277faf2021-05-19 16:45:23 -05005658 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5659 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005660 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005661 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005662 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005663 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005664 return window;
5665 }
5666
5667 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5668 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5669 sp<FakeWindowHandle> window =
5670 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5671 // Generate an arbitrary PID based on the UID
5672 window->setOwnerInfo(1777 + (uid % 10000), uid);
5673 return window;
5674 }
5675
5676 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5677 NotifyMotionArgs args =
5678 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5679 ADISPLAY_ID_DEFAULT, points);
5680 mDispatcher->notifyMotion(&args);
5681 }
5682};
5683
5684TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005685 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005686 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005687 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005688
5689 touch();
5690
5691 mTouchWindow->assertNoEvents();
5692}
5693
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005694TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005695 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5696 const sp<FakeWindowHandle>& w =
5697 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5698 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5699
5700 touch();
5701
5702 mTouchWindow->assertNoEvents();
5703}
5704
5705TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005706 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5707 const sp<FakeWindowHandle>& w =
5708 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5709 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5710
5711 touch();
5712
5713 w->assertNoEvents();
5714}
5715
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005716TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005717 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5718 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005719
5720 touch();
5721
5722 mTouchWindow->consumeAnyMotionDown();
5723}
5724
5725TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005726 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005727 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005728 w->setFrame(Rect(0, 0, 50, 50));
5729 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005730
5731 touch({PointF{100, 100}});
5732
5733 mTouchWindow->consumeAnyMotionDown();
5734}
5735
5736TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005737 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005738 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005739 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5740
5741 touch();
5742
5743 mTouchWindow->consumeAnyMotionDown();
5744}
5745
5746TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5747 const sp<FakeWindowHandle>& w =
5748 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5749 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005750
5751 touch();
5752
5753 mTouchWindow->consumeAnyMotionDown();
5754}
5755
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005756TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5757 const sp<FakeWindowHandle>& w =
5758 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5759 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5760
5761 touch();
5762
5763 w->assertNoEvents();
5764}
5765
5766/**
5767 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5768 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5769 * window, the occluding window will still receive ACTION_OUTSIDE event.
5770 */
5771TEST_F(InputDispatcherUntrustedTouchesTest,
5772 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5773 const sp<FakeWindowHandle>& w =
5774 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005775 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005776 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5777
5778 touch();
5779
5780 w->consumeMotionOutside();
5781}
5782
5783TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5784 const sp<FakeWindowHandle>& w =
5785 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005786 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005787 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5788
5789 touch();
5790
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005791 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005792}
5793
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005794TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005795 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005796 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5797 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005798 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5799
5800 touch();
5801
5802 mTouchWindow->consumeAnyMotionDown();
5803}
5804
5805TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5806 const sp<FakeWindowHandle>& w =
5807 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5808 MAXIMUM_OBSCURING_OPACITY);
5809 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005810
5811 touch();
5812
5813 mTouchWindow->consumeAnyMotionDown();
5814}
5815
5816TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005817 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005818 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5819 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005820 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5821
5822 touch();
5823
5824 mTouchWindow->assertNoEvents();
5825}
5826
5827TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5828 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5829 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005830 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5831 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005832 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005833 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5834 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005835 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5836
5837 touch();
5838
5839 mTouchWindow->assertNoEvents();
5840}
5841
5842TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5843 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5844 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005845 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5846 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005847 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005848 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5849 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005850 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5851
5852 touch();
5853
5854 mTouchWindow->consumeAnyMotionDown();
5855}
5856
5857TEST_F(InputDispatcherUntrustedTouchesTest,
5858 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5859 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005860 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5861 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005862 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005863 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5864 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005865 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5866
5867 touch();
5868
5869 mTouchWindow->consumeAnyMotionDown();
5870}
5871
5872TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5873 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005874 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5875 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005876 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005877 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5878 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005879 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005880
5881 touch();
5882
5883 mTouchWindow->assertNoEvents();
5884}
5885
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005886TEST_F(InputDispatcherUntrustedTouchesTest,
5887 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5888 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005889 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5890 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005891 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005892 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5893 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005894 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5895
5896 touch();
5897
5898 mTouchWindow->assertNoEvents();
5899}
5900
5901TEST_F(InputDispatcherUntrustedTouchesTest,
5902 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5903 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005904 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5905 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005906 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005907 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5908 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005909 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5910
5911 touch();
5912
5913 mTouchWindow->consumeAnyMotionDown();
5914}
5915
5916TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5917 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005918 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5919 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005920 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5921
5922 touch();
5923
5924 mTouchWindow->consumeAnyMotionDown();
5925}
5926
5927TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5928 const sp<FakeWindowHandle>& w =
5929 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5930 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5931
5932 touch();
5933
5934 mTouchWindow->consumeAnyMotionDown();
5935}
5936
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005937TEST_F(InputDispatcherUntrustedTouchesTest,
5938 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5939 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5940 const sp<FakeWindowHandle>& w =
5941 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5942 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5943
5944 touch();
5945
5946 mTouchWindow->assertNoEvents();
5947}
5948
5949TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5950 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5951 const sp<FakeWindowHandle>& w =
5952 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5953 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5954
5955 touch();
5956
5957 mTouchWindow->consumeAnyMotionDown();
5958}
5959
5960TEST_F(InputDispatcherUntrustedTouchesTest,
5961 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5962 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5963 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005964 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5965 OPACITY_ABOVE_THRESHOLD);
5966 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5967
5968 touch();
5969
5970 mTouchWindow->consumeAnyMotionDown();
5971}
5972
5973TEST_F(InputDispatcherUntrustedTouchesTest,
5974 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5975 const sp<FakeWindowHandle>& w1 =
5976 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5977 OPACITY_BELOW_THRESHOLD);
5978 const sp<FakeWindowHandle>& w2 =
5979 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5980 OPACITY_BELOW_THRESHOLD);
5981 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5982
5983 touch();
5984
5985 mTouchWindow->assertNoEvents();
5986}
5987
5988/**
5989 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5990 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5991 * (which alone would result in allowing touches) does not affect the blocking behavior.
5992 */
5993TEST_F(InputDispatcherUntrustedTouchesTest,
5994 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5995 const sp<FakeWindowHandle>& wB =
5996 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5997 OPACITY_BELOW_THRESHOLD);
5998 const sp<FakeWindowHandle>& wC =
5999 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
6000 OPACITY_BELOW_THRESHOLD);
6001 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
6002
6003 touch();
6004
6005 mTouchWindow->assertNoEvents();
6006}
6007
6008/**
6009 * This test is testing that a window from a different UID but with same application token doesn't
6010 * block the touch. Apps can share the application token for close UI collaboration for example.
6011 */
6012TEST_F(InputDispatcherUntrustedTouchesTest,
6013 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
6014 const sp<FakeWindowHandle>& w =
6015 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
6016 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00006017 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
6018
6019 touch();
6020
6021 mTouchWindow->consumeAnyMotionDown();
6022}
6023
arthurhungb89ccb02020-12-30 16:19:01 +08006024class InputDispatcherDragTests : public InputDispatcherTest {
6025protected:
6026 std::shared_ptr<FakeApplicationHandle> mApp;
6027 sp<FakeWindowHandle> mWindow;
6028 sp<FakeWindowHandle> mSecondWindow;
6029 sp<FakeWindowHandle> mDragWindow;
6030
6031 void SetUp() override {
6032 InputDispatcherTest::SetUp();
6033 mApp = std::make_shared<FakeApplicationHandle>();
6034 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6035 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006036
6037 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6038 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08006039
6040 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6041 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6042 }
6043
6044 // Start performing drag, we will create a drag window and transfer touch to it.
6045 void performDrag() {
6046 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6047 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6048 {50, 50}))
6049 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6050
6051 // Window should receive motion event.
6052 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6053
6054 // The drag window covers the entire display
6055 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
6056 mDispatcher->setInputWindows(
6057 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6058
6059 // Transfer touch focus to the drag window
6060 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6061 true /* isDragDrop */);
6062 mWindow->consumeMotionCancel();
6063 mDragWindow->consumeMotionDown();
6064 }
arthurhung6d4bed92021-03-17 11:59:33 +08006065
6066 // Start performing drag, we will create a drag window and transfer touch to it.
6067 void performStylusDrag() {
6068 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6069 injectMotionEvent(mDispatcher,
6070 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6071 AINPUT_SOURCE_STYLUS)
6072 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6073 .pointer(PointerBuilder(0,
6074 AMOTION_EVENT_TOOL_TYPE_STYLUS)
6075 .x(50)
6076 .y(50))
6077 .build()));
6078 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6079
6080 // The drag window covers the entire display
6081 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
6082 mDispatcher->setInputWindows(
6083 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6084
6085 // Transfer touch focus to the drag window
6086 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6087 true /* isDragDrop */);
6088 mWindow->consumeMotionCancel();
6089 mDragWindow->consumeMotionDown();
6090 }
arthurhungb89ccb02020-12-30 16:19:01 +08006091};
6092
6093TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
6094 performDrag();
6095
6096 // Move on window.
6097 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6098 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6099 ADISPLAY_ID_DEFAULT, {50, 50}))
6100 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6101 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6102 mWindow->consumeDragEvent(false, 50, 50);
6103 mSecondWindow->assertNoEvents();
6104
6105 // Move to another window.
6106 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6107 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6108 ADISPLAY_ID_DEFAULT, {150, 50}))
6109 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6110 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6111 mWindow->consumeDragEvent(true, 150, 50);
6112 mSecondWindow->consumeDragEvent(false, 50, 50);
6113
6114 // Move back to original window.
6115 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6116 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6117 ADISPLAY_ID_DEFAULT, {50, 50}))
6118 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6119 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6120 mWindow->consumeDragEvent(false, 50, 50);
6121 mSecondWindow->consumeDragEvent(true, -50, 50);
6122
6123 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6124 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6125 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6126 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6127 mWindow->assertNoEvents();
6128 mSecondWindow->assertNoEvents();
6129}
6130
arthurhungf452d0b2021-01-06 00:19:52 +08006131TEST_F(InputDispatcherDragTests, DragAndDrop) {
6132 performDrag();
6133
6134 // Move on window.
6135 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6136 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6137 ADISPLAY_ID_DEFAULT, {50, 50}))
6138 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6139 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6140 mWindow->consumeDragEvent(false, 50, 50);
6141 mSecondWindow->assertNoEvents();
6142
6143 // Move to another window.
6144 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6145 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6146 ADISPLAY_ID_DEFAULT, {150, 50}))
6147 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6148 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6149 mWindow->consumeDragEvent(true, 150, 50);
6150 mSecondWindow->consumeDragEvent(false, 50, 50);
6151
6152 // drop to another window.
6153 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6154 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6155 {150, 50}))
6156 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6157 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6158 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6159 mWindow->assertNoEvents();
6160 mSecondWindow->assertNoEvents();
6161}
6162
arthurhung6d4bed92021-03-17 11:59:33 +08006163TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6164 performStylusDrag();
6165
6166 // Move on window and keep button pressed.
6167 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6168 injectMotionEvent(mDispatcher,
6169 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6170 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6171 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6172 .x(50)
6173 .y(50))
6174 .build()))
6175 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6176 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6177 mWindow->consumeDragEvent(false, 50, 50);
6178 mSecondWindow->assertNoEvents();
6179
6180 // Move to another window and release button, expect to drop item.
6181 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6182 injectMotionEvent(mDispatcher,
6183 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6184 .buttonState(0)
6185 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6186 .x(150)
6187 .y(50))
6188 .build()))
6189 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6190 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6191 mWindow->assertNoEvents();
6192 mSecondWindow->assertNoEvents();
6193 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6194
6195 // nothing to the window.
6196 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6197 injectMotionEvent(mDispatcher,
6198 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6199 .buttonState(0)
6200 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6201 .x(150)
6202 .y(50))
6203 .build()))
6204 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6205 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6206 mWindow->assertNoEvents();
6207 mSecondWindow->assertNoEvents();
6208}
6209
Arthur Hung6d0571e2021-04-09 20:18:16 +08006210TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6211 performDrag();
6212
6213 // Set second window invisible.
6214 mSecondWindow->setVisible(false);
6215 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6216
6217 // Move on window.
6218 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6219 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6220 ADISPLAY_ID_DEFAULT, {50, 50}))
6221 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6222 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6223 mWindow->consumeDragEvent(false, 50, 50);
6224 mSecondWindow->assertNoEvents();
6225
6226 // Move to another window.
6227 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6228 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6229 ADISPLAY_ID_DEFAULT, {150, 50}))
6230 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6231 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6232 mWindow->consumeDragEvent(true, 150, 50);
6233 mSecondWindow->assertNoEvents();
6234
6235 // drop to another window.
6236 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6237 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6238 {150, 50}))
6239 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6240 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6241 mFakePolicy->assertDropTargetEquals(nullptr);
6242 mWindow->assertNoEvents();
6243 mSecondWindow->assertNoEvents();
6244}
6245
Vishnu Nair062a8672021-09-03 16:07:44 -07006246class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6247
6248TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6249 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6250 sp<FakeWindowHandle> window =
6251 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006252 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006253 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6254 window->setFocusable(true);
6255 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6256 setFocusedWindow(window);
6257 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6258
6259 // With the flag set, window should not get any input
6260 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6261 mDispatcher->notifyKey(&keyArgs);
6262 window->assertNoEvents();
6263
6264 NotifyMotionArgs motionArgs =
6265 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6266 ADISPLAY_ID_DEFAULT);
6267 mDispatcher->notifyMotion(&motionArgs);
6268 window->assertNoEvents();
6269
6270 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006271 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006272 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6273
6274 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6275 mDispatcher->notifyKey(&keyArgs);
6276 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6277
6278 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6279 ADISPLAY_ID_DEFAULT);
6280 mDispatcher->notifyMotion(&motionArgs);
6281 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6282 window->assertNoEvents();
6283}
6284
6285TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6286 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6287 std::make_shared<FakeApplicationHandle>();
6288 sp<FakeWindowHandle> obscuringWindow =
6289 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6290 ADISPLAY_ID_DEFAULT);
6291 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6292 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006293 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006294 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6295 sp<FakeWindowHandle> window =
6296 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006297 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006298 window->setOwnerInfo(222, 222);
6299 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6300 window->setFocusable(true);
6301 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6302 setFocusedWindow(window);
6303 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6304
6305 // With the flag set, window should not get any input
6306 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6307 mDispatcher->notifyKey(&keyArgs);
6308 window->assertNoEvents();
6309
6310 NotifyMotionArgs motionArgs =
6311 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6312 ADISPLAY_ID_DEFAULT);
6313 mDispatcher->notifyMotion(&motionArgs);
6314 window->assertNoEvents();
6315
6316 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006317 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006318 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6319
6320 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6321 mDispatcher->notifyKey(&keyArgs);
6322 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6323
6324 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6325 ADISPLAY_ID_DEFAULT);
6326 mDispatcher->notifyMotion(&motionArgs);
6327 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6328 window->assertNoEvents();
6329}
6330
6331TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6332 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6333 std::make_shared<FakeApplicationHandle>();
6334 sp<FakeWindowHandle> obscuringWindow =
6335 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6336 ADISPLAY_ID_DEFAULT);
6337 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6338 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006339 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006340 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6341 sp<FakeWindowHandle> window =
6342 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006343 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006344 window->setOwnerInfo(222, 222);
6345 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6346 window->setFocusable(true);
6347 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6348 setFocusedWindow(window);
6349 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6350
6351 // With the flag set, window should not get any input
6352 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6353 mDispatcher->notifyKey(&keyArgs);
6354 window->assertNoEvents();
6355
6356 NotifyMotionArgs motionArgs =
6357 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6358 ADISPLAY_ID_DEFAULT);
6359 mDispatcher->notifyMotion(&motionArgs);
6360 window->assertNoEvents();
6361
6362 // When the window is no longer obscured because it went on top, it should get input
6363 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6364
6365 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6366 mDispatcher->notifyKey(&keyArgs);
6367 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6368
6369 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6370 ADISPLAY_ID_DEFAULT);
6371 mDispatcher->notifyMotion(&motionArgs);
6372 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6373 window->assertNoEvents();
6374}
6375
Antonio Kantekf16f2832021-09-28 04:39:20 +00006376class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6377protected:
6378 std::shared_ptr<FakeApplicationHandle> mApp;
6379 sp<FakeWindowHandle> mWindow;
6380 sp<FakeWindowHandle> mSecondWindow;
6381
6382 void SetUp() override {
6383 InputDispatcherTest::SetUp();
6384
6385 mApp = std::make_shared<FakeApplicationHandle>();
6386 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6387 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006388 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006389 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6390 mSecondWindow->setFocusable(true);
6391
6392 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6393 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006394 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006395
6396 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
6397 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, INJECTOR_PID,
6398 INJECTOR_UID, /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006399 }
6400
Antonio Kantekea47acb2021-12-23 12:41:25 -08006401 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006402 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006403 mWindow->consumeTouchModeEvent(inTouchMode);
6404 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6405 }
6406};
6407
Antonio Kantek26defcf2022-02-08 01:12:27 +00006408TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006409 const WindowInfo& windowInfo = *mWindow->getInfo();
6410 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6411 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006412}
6413
Antonio Kantek26defcf2022-02-08 01:12:27 +00006414TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6415 const WindowInfo& windowInfo = *mWindow->getInfo();
6416 int32_t ownerPid = windowInfo.ownerPid;
6417 int32_t ownerUid = windowInfo.ownerUid;
6418 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6419 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6420 ownerUid, /* hasPermission */ false));
6421 mWindow->assertNoEvents();
6422 mSecondWindow->assertNoEvents();
6423}
6424
6425TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6426 const WindowInfo& windowInfo = *mWindow->getInfo();
6427 int32_t ownerPid = windowInfo.ownerPid;
6428 int32_t ownerUid = windowInfo.ownerUid;
6429 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6430 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6431 /* hasPermission */ true);
6432}
6433
Antonio Kantekf16f2832021-09-28 04:39:20 +00006434TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006435 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006436 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6437 windowInfo.ownerPid, windowInfo.ownerUid,
6438 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006439 mWindow->assertNoEvents();
6440 mSecondWindow->assertNoEvents();
6441}
6442
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006443class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6444public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006445 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006446 std::shared_ptr<FakeApplicationHandle> application =
6447 std::make_shared<FakeApplicationHandle>();
6448 std::string name = "Fake Spy ";
6449 name += std::to_string(mSpyCount++);
6450 sp<FakeWindowHandle> spy =
6451 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006452 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006453 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006454 return spy;
6455 }
6456
6457 sp<FakeWindowHandle> createForeground() {
6458 std::shared_ptr<FakeApplicationHandle> application =
6459 std::make_shared<FakeApplicationHandle>();
6460 sp<FakeWindowHandle> window =
6461 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006462 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006463 return window;
6464 }
6465
6466private:
6467 int mSpyCount{0};
6468};
6469
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006470using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006471/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006472 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6473 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006474TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6475 ScopedSilentDeath _silentDeath;
6476
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006477 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006478 spy->setTrustedOverlay(false);
6479 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6480 ".* not a trusted overlay");
6481}
6482
6483/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006484 * Input injection into a display with a spy window but no foreground windows should succeed.
6485 */
6486TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006487 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006488 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6489
6490 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6491 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6492 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6493 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6494}
6495
6496/**
6497 * Verify the order in which different input windows receive events. The touched foreground window
6498 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6499 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6500 * receive events before ones belows it.
6501 *
6502 * Here, we set up a scenario with four windows in the following Z order from the top:
6503 * spy1, spy2, window, spy3.
6504 * We then inject an event and verify that the foreground "window" receives it first, followed by
6505 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6506 * window.
6507 */
6508TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6509 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006510 auto spy1 = createSpy();
6511 auto spy2 = createSpy();
6512 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006513 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6514 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6515 const size_t numChannels = channels.size();
6516
Michael Wright8e9a8562022-02-09 13:44:29 +00006517 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006518 if (!epollFd.ok()) {
6519 FAIL() << "Failed to create epoll fd";
6520 }
6521
6522 for (size_t i = 0; i < numChannels; i++) {
6523 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6524 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6525 FAIL() << "Failed to add fd to epoll";
6526 }
6527 }
6528
6529 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6530 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6531 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6532
6533 std::vector<size_t> eventOrder;
6534 std::vector<struct epoll_event> events(numChannels);
6535 for (;;) {
6536 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6537 (100ms).count());
6538 if (nFds < 0) {
6539 FAIL() << "Failed to call epoll_wait";
6540 }
6541 if (nFds == 0) {
6542 break; // epoll_wait timed out
6543 }
6544 for (int i = 0; i < nFds; i++) {
6545 ASSERT_EQ(EPOLLIN, events[i].events);
6546 eventOrder.push_back(events[i].data.u64);
6547 channels[i]->consumeMotionDown();
6548 }
6549 }
6550
6551 // Verify the order in which the events were received.
6552 EXPECT_EQ(3u, eventOrder.size());
6553 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6554 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6555 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6556}
6557
6558/**
6559 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6560 */
6561TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6562 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006563 auto spy = createSpy();
6564 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006565 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6566
6567 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6568 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6569 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6570 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6571 spy->assertNoEvents();
6572}
6573
6574/**
6575 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6576 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6577 * to the window.
6578 */
6579TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6580 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006581 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006582 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6583 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6584
6585 // Inject an event outside the spy window's touchable region.
6586 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6587 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6588 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6589 window->consumeMotionDown();
6590 spy->assertNoEvents();
6591 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6592 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6593 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6594 window->consumeMotionUp();
6595 spy->assertNoEvents();
6596
6597 // Inject an event inside the spy window's touchable region.
6598 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6599 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6600 {5, 10}))
6601 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6602 window->consumeMotionDown();
6603 spy->consumeMotionDown();
6604}
6605
6606/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006607 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006608 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006609 */
6610TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6611 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006612 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006613 auto spy = createSpy();
6614 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006615 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006616 spy->setFrame(Rect{0, 0, 20, 20});
6617 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6618
6619 // Inject an event outside the spy window's frame and touchable region.
6620 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006621 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6622 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006623 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6624 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006625 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006626}
6627
6628/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006629 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6630 * any other windows - including other spy windows - will also be cancelled.
6631 */
6632TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6633 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006634 auto spy1 = createSpy();
6635 auto spy2 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6637
6638 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6639 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6640 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6641 window->consumeMotionDown();
6642 spy1->consumeMotionDown();
6643 spy2->consumeMotionDown();
6644
6645 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006646 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006647 spy2->assertNoEvents();
6648 spy1->consumeMotionCancel();
6649 window->consumeMotionCancel();
6650
6651 // The rest of the gesture should only be sent to the second spy window.
6652 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6653 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6654 ADISPLAY_ID_DEFAULT))
6655 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6656 spy2->consumeMotionMove();
6657 spy1->assertNoEvents();
6658 window->assertNoEvents();
6659}
6660
6661/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006662 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
6663 * in the middle of the gesture.
6664 */
6665TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
6666 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006667 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006668 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6669
6670 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6671 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6672 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6673 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6674 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6675
6676 window->releaseChannel();
6677
6678 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6679
6680 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6681 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6682 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6683 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6684}
6685
6686/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006687 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
6688 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006689 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006690TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006691 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006692 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006693
6694 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6695
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006696 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006697 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6698 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6699 {100, 200}))
6700 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006701 spy->consumeMotionDown();
6702 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006703
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006704 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006705 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006706 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006707
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006708 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006709 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006710 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006711 .displayId(ADISPLAY_ID_DEFAULT)
6712 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6713 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6714 .x(100)
6715 .y(200))
6716 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6717 .build();
6718 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6719 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6720 InputEventInjectionSync::WAIT_FOR_RESULT))
6721 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6722
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006723 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6724
6725 // Third finger goes down outside all windows, so injection should fail.
6726 const MotionEvent thirdFingerDownEvent =
6727 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6728 (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6729 AINPUT_SOURCE_TOUCHSCREEN)
6730 .displayId(ADISPLAY_ID_DEFAULT)
6731 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6732 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6733 .x(100)
6734 .y(200))
6735 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6736 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
6737 .build();
6738 ASSERT_EQ(InputEventInjectionResult::FAILED,
6739 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
6740 InputEventInjectionSync::WAIT_FOR_RESULT))
6741 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6742
6743 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006744 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006745}
6746
6747/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006748 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6749 * pointers that are down within its bounds.
6750 */
6751TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6752 auto windowLeft = createForeground();
6753 windowLeft->setFrame({0, 0, 100, 200});
6754 auto windowRight = createForeground();
6755 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006756 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006757 spy->setFrame({0, 0, 200, 200});
6758 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6759
6760 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6761 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6762 {50, 50}))
6763 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6764 windowLeft->consumeMotionDown();
6765 spy->consumeMotionDown();
6766
6767 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006768 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006769 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6770 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6771 .pointer(
6772 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6773 .build();
6774 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6775 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6776 InputEventInjectionSync::WAIT_FOR_RESULT))
6777 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6778 windowRight->consumeMotionDown();
6779 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6780}
6781
6782/**
6783 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6784 * the spy should receive the second pointer with ACTION_DOWN.
6785 */
6786TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6787 auto window = createForeground();
6788 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006789 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006790 spyRight->setFrame({100, 0, 200, 200});
6791 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6792
6793 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6794 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6795 {50, 50}))
6796 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6797 window->consumeMotionDown();
6798 spyRight->assertNoEvents();
6799
6800 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006801 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006802 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6803 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6804 .pointer(
6805 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6806 .build();
6807 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6808 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6809 InputEventInjectionSync::WAIT_FOR_RESULT))
6810 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6811 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6812 spyRight->consumeMotionDown();
6813}
6814
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006815/**
6816 * The spy window should not be able to affect whether or not touches are split. Only the foreground
6817 * windows should be allowed to control split touch.
6818 */
6819TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006820 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006821 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006822 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006823 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006824
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006825 auto window = createForeground();
6826 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006827
6828 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6829
6830 // First finger down, no window touched.
6831 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6832 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6833 {100, 200}))
6834 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6835 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6836 window->assertNoEvents();
6837
6838 // Second finger down on window, the window should receive touch down.
6839 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006840 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006841 .displayId(ADISPLAY_ID_DEFAULT)
6842 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6843 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6844 .x(100)
6845 .y(200))
6846 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6847 .build();
6848 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6849 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6850 InputEventInjectionSync::WAIT_FOR_RESULT))
6851 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6852
6853 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6854 spy->consumeMotionPointerDown(1 /* pointerIndex */);
6855}
6856
6857/**
6858 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
6859 * do not receive key events.
6860 */
6861TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006862 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006863 spy->setFocusable(false);
6864
6865 auto window = createForeground();
6866 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6867 setFocusedWindow(window);
6868 window->consumeFocusEvent(true);
6869
6870 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6871 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6872 window->consumeKeyDown(ADISPLAY_ID_NONE);
6873
6874 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6875 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6876 window->consumeKeyUp(ADISPLAY_ID_NONE);
6877
6878 spy->assertNoEvents();
6879}
6880
Prabir Pradhand65552b2021-10-07 11:23:50 -07006881class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6882public:
6883 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6884 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6885 std::make_shared<FakeApplicationHandle>();
6886 sp<FakeWindowHandle> overlay =
6887 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6888 ADISPLAY_ID_DEFAULT);
6889 overlay->setFocusable(false);
6890 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006891 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006892 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006893 overlay->setTrustedOverlay(true);
6894
6895 std::shared_ptr<FakeApplicationHandle> application =
6896 std::make_shared<FakeApplicationHandle>();
6897 sp<FakeWindowHandle> window =
6898 new FakeWindowHandle(application, mDispatcher, "Application window",
6899 ADISPLAY_ID_DEFAULT);
6900 window->setFocusable(true);
6901 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006902
6903 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6904 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6905 setFocusedWindow(window);
6906 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6907 return {std::move(overlay), std::move(window)};
6908 }
6909
6910 void sendFingerEvent(int32_t action) {
6911 NotifyMotionArgs motionArgs =
6912 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6913 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6914 mDispatcher->notifyMotion(&motionArgs);
6915 }
6916
6917 void sendStylusEvent(int32_t action) {
6918 NotifyMotionArgs motionArgs =
6919 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6920 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6921 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6922 mDispatcher->notifyMotion(&motionArgs);
6923 }
6924};
6925
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006926using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
6927
6928TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
6929 ScopedSilentDeath _silentDeath;
6930
Prabir Pradhand65552b2021-10-07 11:23:50 -07006931 auto [overlay, window] = setupStylusOverlayScenario();
6932 overlay->setTrustedOverlay(false);
6933 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6934 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6935 ".* not a trusted overlay");
6936}
6937
6938TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6939 auto [overlay, window] = setupStylusOverlayScenario();
6940 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6941
6942 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6943 overlay->consumeMotionDown();
6944 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6945 overlay->consumeMotionUp();
6946
6947 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6948 window->consumeMotionDown();
6949 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6950 window->consumeMotionUp();
6951
6952 overlay->assertNoEvents();
6953 window->assertNoEvents();
6954}
6955
6956TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6957 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006958 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006959 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6960
6961 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6962 overlay->consumeMotionDown();
6963 window->consumeMotionDown();
6964 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6965 overlay->consumeMotionUp();
6966 window->consumeMotionUp();
6967
6968 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6969 window->consumeMotionDown();
6970 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6971 window->consumeMotionUp();
6972
6973 overlay->assertNoEvents();
6974 window->assertNoEvents();
6975}
6976
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00006977/**
6978 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
6979 * The scenario is as follows:
6980 * - The stylus interceptor overlay is configured as a spy window.
6981 * - The stylus interceptor spy receives the start of a new stylus gesture.
6982 * - It pilfers pointers and then configures itself to no longer be a spy.
6983 * - The stylus interceptor continues to receive the rest of the gesture.
6984 */
6985TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
6986 auto [overlay, window] = setupStylusOverlayScenario();
6987 overlay->setSpy(true);
6988 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6989
6990 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6991 overlay->consumeMotionDown();
6992 window->consumeMotionDown();
6993
6994 // The interceptor pilfers the pointers.
6995 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
6996 window->consumeMotionCancel();
6997
6998 // The interceptor configures itself so that it is no longer a spy.
6999 overlay->setSpy(false);
7000 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
7001
7002 // It continues to receive the rest of the stylus gesture.
7003 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
7004 overlay->consumeMotionMove();
7005 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
7006 overlay->consumeMotionUp();
7007
7008 window->assertNoEvents();
7009}
7010
Garfield Tane84e6f92019-08-29 17:28:41 -07007011} // namespace android::inputdispatcher