blob: bf587050c6196d00729ac28d3af373d7750c6425 [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 Vishniakoud0c6bc82021-03-13 03:14:52 +00002429TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002430 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002431
2432 PointF touchPoint = {10, 10};
2433
2434 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002435 sp<FakeWindowHandle> firstWindow =
2436 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002437 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002438 sp<FakeWindowHandle> secondWindow =
2439 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002440 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002441
2442 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002443 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002444
2445 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002446 NotifyMotionArgs downMotionArgs =
2447 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2448 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002449 mDispatcher->notifyMotion(&downMotionArgs);
2450 // Only the first window should get the down event
2451 firstWindow->consumeMotionDown();
2452 secondWindow->assertNoEvents();
2453
2454 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002455 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002456 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002457 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002458 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2459 // Only the first window should get the pointer down event
2460 firstWindow->consumeMotionPointerDown(1);
2461 secondWindow->assertNoEvents();
2462
2463 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002464 TransferFunction f = GetParam();
2465 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2466 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002467 // The first window gets cancel and the second gets down and pointer down
2468 firstWindow->consumeMotionCancel();
2469 secondWindow->consumeMotionDown();
2470 secondWindow->consumeMotionPointerDown(1);
2471
2472 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002473 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002474 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002475 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002476 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2477 // The first window gets nothing and the second gets pointer up
2478 firstWindow->assertNoEvents();
2479 secondWindow->consumeMotionPointerUp(1);
2480
2481 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002482 NotifyMotionArgs upMotionArgs =
2483 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2484 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002485 mDispatcher->notifyMotion(&upMotionArgs);
2486 // The first window gets nothing and the second gets up
2487 firstWindow->assertNoEvents();
2488 secondWindow->consumeMotionUp();
2489}
2490
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002491// For the cases of single pointer touch and two pointers non-split touch, the api's
2492// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2493// for the case where there are multiple pointers split across several windows.
2494INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2495 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002496 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2497 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002498 return dispatcher->transferTouch(destChannelToken);
2499 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002500 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2501 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002502 return dispatcher->transferTouchFocus(from, to,
2503 false /*isDragAndDrop*/);
2504 }));
2505
Svet Ganov5d3bc372020-01-26 23:11:07 -08002506TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002507 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002508
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002509 sp<FakeWindowHandle> firstWindow =
2510 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002511 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002512
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002513 sp<FakeWindowHandle> secondWindow =
2514 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002515 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002516
2517 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002518 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002519
2520 PointF pointInFirst = {300, 200};
2521 PointF pointInSecond = {300, 600};
2522
2523 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002524 NotifyMotionArgs firstDownMotionArgs =
2525 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2526 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002527 mDispatcher->notifyMotion(&firstDownMotionArgs);
2528 // Only the first window should get the down event
2529 firstWindow->consumeMotionDown();
2530 secondWindow->assertNoEvents();
2531
2532 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002533 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002534 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002535 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002536 mDispatcher->notifyMotion(&secondDownMotionArgs);
2537 // The first window gets a move and the second a down
2538 firstWindow->consumeMotionMove();
2539 secondWindow->consumeMotionDown();
2540
2541 // Transfer touch focus to the second window
2542 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2543 // The first window gets cancel and the new gets pointer down (it already saw down)
2544 firstWindow->consumeMotionCancel();
2545 secondWindow->consumeMotionPointerDown(1);
2546
2547 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002548 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002549 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002550 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002551 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2552 // The first window gets nothing and the second gets pointer up
2553 firstWindow->assertNoEvents();
2554 secondWindow->consumeMotionPointerUp(1);
2555
2556 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002557 NotifyMotionArgs upMotionArgs =
2558 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2559 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002560 mDispatcher->notifyMotion(&upMotionArgs);
2561 // The first window gets nothing and the second gets up
2562 firstWindow->assertNoEvents();
2563 secondWindow->consumeMotionUp();
2564}
2565
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002566// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2567// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2568// touch is not supported, so the touch should continue on those windows and the transferred-to
2569// window should get nothing.
2570TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2571 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2572
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002573 sp<FakeWindowHandle> firstWindow =
2574 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2575 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002576
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002577 sp<FakeWindowHandle> secondWindow =
2578 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2579 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002580
2581 // Add the windows to the dispatcher
2582 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2583
2584 PointF pointInFirst = {300, 200};
2585 PointF pointInSecond = {300, 600};
2586
2587 // Send down to the first window
2588 NotifyMotionArgs firstDownMotionArgs =
2589 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2590 ADISPLAY_ID_DEFAULT, {pointInFirst});
2591 mDispatcher->notifyMotion(&firstDownMotionArgs);
2592 // Only the first window should get the down event
2593 firstWindow->consumeMotionDown();
2594 secondWindow->assertNoEvents();
2595
2596 // Send down to the second window
2597 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002598 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002599 {pointInFirst, pointInSecond});
2600 mDispatcher->notifyMotion(&secondDownMotionArgs);
2601 // The first window gets a move and the second a down
2602 firstWindow->consumeMotionMove();
2603 secondWindow->consumeMotionDown();
2604
2605 // Transfer touch focus to the second window
2606 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2607 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2608 ASSERT_FALSE(transferred);
2609 firstWindow->assertNoEvents();
2610 secondWindow->assertNoEvents();
2611
2612 // The rest of the dispatch should proceed as normal
2613 // Send pointer up to the second window
2614 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002615 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002616 {pointInFirst, pointInSecond});
2617 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2618 // The first window gets MOVE and the second gets pointer up
2619 firstWindow->consumeMotionMove();
2620 secondWindow->consumeMotionUp();
2621
2622 // Send up event to the first window
2623 NotifyMotionArgs upMotionArgs =
2624 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2625 ADISPLAY_ID_DEFAULT);
2626 mDispatcher->notifyMotion(&upMotionArgs);
2627 // The first window gets nothing and the second gets up
2628 firstWindow->consumeMotionUp();
2629 secondWindow->assertNoEvents();
2630}
2631
Arthur Hungabbb9d82021-09-01 14:52:30 +00002632// This case will create two windows and one mirrored window on the default display and mirror
2633// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2634// the windows info of second display before default display.
2635TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2636 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2637 sp<FakeWindowHandle> firstWindowInPrimary =
2638 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2639 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002640 sp<FakeWindowHandle> secondWindowInPrimary =
2641 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2642 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002643
2644 sp<FakeWindowHandle> mirrorWindowInPrimary =
2645 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2646 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002647
2648 sp<FakeWindowHandle> firstWindowInSecondary =
2649 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2650 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002651
2652 sp<FakeWindowHandle> secondWindowInSecondary =
2653 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2654 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002655
2656 // Update window info, let it find window handle of second display first.
2657 mDispatcher->setInputWindows(
2658 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2659 {ADISPLAY_ID_DEFAULT,
2660 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2661
2662 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2663 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2664 {50, 50}))
2665 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2666
2667 // Window should receive motion event.
2668 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2669
2670 // Transfer touch focus
2671 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2672 secondWindowInPrimary->getToken()));
2673 // The first window gets cancel.
2674 firstWindowInPrimary->consumeMotionCancel();
2675 secondWindowInPrimary->consumeMotionDown();
2676
2677 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2678 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2679 ADISPLAY_ID_DEFAULT, {150, 50}))
2680 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2681 firstWindowInPrimary->assertNoEvents();
2682 secondWindowInPrimary->consumeMotionMove();
2683
2684 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2685 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2686 {150, 50}))
2687 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2688 firstWindowInPrimary->assertNoEvents();
2689 secondWindowInPrimary->consumeMotionUp();
2690}
2691
2692// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2693// 'transferTouch' api.
2694TEST_F(InputDispatcherTest, TransferTouch_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 // Touch on second display.
2722 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2723 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2724 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2725
2726 // Window should receive motion event.
2727 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2728
2729 // Transfer touch focus
2730 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2731
2732 // The first window gets cancel.
2733 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2734 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2735
2736 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2737 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2738 SECOND_DISPLAY_ID, {150, 50}))
2739 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2740 firstWindowInPrimary->assertNoEvents();
2741 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2742
2743 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2744 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2745 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2746 firstWindowInPrimary->assertNoEvents();
2747 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2748}
2749
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002750TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002751 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002752 sp<FakeWindowHandle> window =
2753 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2754
Vishnu Nair47074b82020-08-14 11:54:47 -07002755 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002756 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002757 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002758
2759 window->consumeFocusEvent(true);
2760
2761 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2762 mDispatcher->notifyKey(&keyArgs);
2763
2764 // Window should receive key down event.
2765 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2766}
2767
2768TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002769 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002770 sp<FakeWindowHandle> window =
2771 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2772
Arthur Hung72d8dc32020-03-28 00:48:39 +00002773 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002774
2775 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2776 mDispatcher->notifyKey(&keyArgs);
2777 mDispatcher->waitForIdle();
2778
2779 window->assertNoEvents();
2780}
2781
2782// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2783TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002784 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002785 sp<FakeWindowHandle> window =
2786 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2787
Arthur Hung72d8dc32020-03-28 00:48:39 +00002788 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002789
2790 // Send key
2791 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2792 mDispatcher->notifyKey(&keyArgs);
2793 // Send motion
2794 NotifyMotionArgs motionArgs =
2795 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2796 ADISPLAY_ID_DEFAULT);
2797 mDispatcher->notifyMotion(&motionArgs);
2798
2799 // Window should receive only the motion event
2800 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2801 window->assertNoEvents(); // Key event or focus event will not be received
2802}
2803
arthurhungea3f4fc2020-12-21 23:18:53 +08002804TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2805 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2806
arthurhungea3f4fc2020-12-21 23:18:53 +08002807 sp<FakeWindowHandle> firstWindow =
2808 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2809 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08002810
arthurhungea3f4fc2020-12-21 23:18:53 +08002811 sp<FakeWindowHandle> secondWindow =
2812 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2813 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08002814
2815 // Add the windows to the dispatcher
2816 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2817
2818 PointF pointInFirst = {300, 200};
2819 PointF pointInSecond = {300, 600};
2820
2821 // Send down to the first window
2822 NotifyMotionArgs firstDownMotionArgs =
2823 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2824 ADISPLAY_ID_DEFAULT, {pointInFirst});
2825 mDispatcher->notifyMotion(&firstDownMotionArgs);
2826 // Only the first window should get the down event
2827 firstWindow->consumeMotionDown();
2828 secondWindow->assertNoEvents();
2829
2830 // Send down to the second window
2831 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002832 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08002833 {pointInFirst, pointInSecond});
2834 mDispatcher->notifyMotion(&secondDownMotionArgs);
2835 // The first window gets a move and the second a down
2836 firstWindow->consumeMotionMove();
2837 secondWindow->consumeMotionDown();
2838
2839 // Send pointer cancel to the second window
2840 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002841 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08002842 {pointInFirst, pointInSecond});
2843 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2844 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2845 // The first window gets move and the second gets cancel.
2846 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2847 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2848
2849 // Send up event.
2850 NotifyMotionArgs upMotionArgs =
2851 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2852 ADISPLAY_ID_DEFAULT);
2853 mDispatcher->notifyMotion(&upMotionArgs);
2854 // The first window gets up and the second gets nothing.
2855 firstWindow->consumeMotionUp();
2856 secondWindow->assertNoEvents();
2857}
2858
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002859TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2860 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2861
2862 sp<FakeWindowHandle> window =
2863 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2864 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2865 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2866 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2867 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2868
2869 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2870 window->assertNoEvents();
2871 mDispatcher->waitForIdle();
2872}
2873
chaviwd1c23182019-12-20 18:44:56 -08002874class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002875public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002876 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002877 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07002878 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002879 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002880 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002881 }
2882
chaviwd1c23182019-12-20 18:44:56 -08002883 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2884
2885 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2886 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2887 expectedDisplayId, expectedFlags);
2888 }
2889
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002890 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2891
2892 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2893
chaviwd1c23182019-12-20 18:44:56 -08002894 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2895 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2896 expectedDisplayId, expectedFlags);
2897 }
2898
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002899 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2900 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2901 expectedDisplayId, expectedFlags);
2902 }
2903
chaviwd1c23182019-12-20 18:44:56 -08002904 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2905 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2906 expectedDisplayId, expectedFlags);
2907 }
2908
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002909 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2910 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2911 expectedDisplayId, expectedFlags);
2912 }
2913
Arthur Hungfbfa5722021-11-16 02:45:54 +00002914 void consumeMotionPointerDown(int32_t pointerIdx) {
2915 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2916 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2917 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2918 0 /*expectedFlags*/);
2919 }
2920
Evan Rosky84f07f02021-04-16 10:42:42 -07002921 MotionEvent* consumeMotion() {
2922 InputEvent* event = mInputReceiver->consume();
2923 if (!event) {
2924 ADD_FAILURE() << "No event was produced";
2925 return nullptr;
2926 }
2927 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2928 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2929 return nullptr;
2930 }
2931 return static_cast<MotionEvent*>(event);
2932 }
2933
chaviwd1c23182019-12-20 18:44:56 -08002934 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2935
2936private:
2937 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002938};
2939
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002940using InputDispatcherMonitorTest = InputDispatcherTest;
2941
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002942/**
2943 * Two entities that receive touch: A window, and a global monitor.
2944 * The touch goes to the window, and then the window disappears.
2945 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2946 * for the monitor, as well.
2947 * 1. foregroundWindow
2948 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2949 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002950TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002951 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2952 sp<FakeWindowHandle> window =
2953 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2954
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002955 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002956
2957 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2958 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2959 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2960 {100, 200}))
2961 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2962
2963 // Both the foreground window and the global monitor should receive the touch down
2964 window->consumeMotionDown();
2965 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2966
2967 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2968 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2969 ADISPLAY_ID_DEFAULT, {110, 200}))
2970 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2971
2972 window->consumeMotionMove();
2973 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2974
2975 // Now the foreground window goes away
2976 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2977 window->consumeMotionCancel();
2978 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2979
2980 // If more events come in, there will be no more foreground window to send them to. This will
2981 // cause a cancel for the monitor, as well.
2982 ASSERT_EQ(InputEventInjectionResult::FAILED,
2983 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2984 ADISPLAY_ID_DEFAULT, {120, 200}))
2985 << "Injection should fail because the window was removed";
2986 window->assertNoEvents();
2987 // Global monitor now gets the cancel
2988 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2989}
2990
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002991TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002992 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002993 sp<FakeWindowHandle> window =
2994 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002995 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002996
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002997 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002998
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002999 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003000 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003001 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003002 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003003 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003004}
3005
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003006TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3007 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003008
Chris Yea209fde2020-07-22 13:54:51 -07003009 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003010 sp<FakeWindowHandle> window =
3011 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003012 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003013
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003014 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003015 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003016 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003017 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003018 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003019
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003020 // Pilfer pointers from the monitor.
3021 // This should not do anything and the window should continue to receive events.
3022 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003023
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003024 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003025 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3026 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003027 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003028
3029 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3030 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003031}
3032
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003033TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003034 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3035 sp<FakeWindowHandle> window =
3036 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3037 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3038 window->setWindowOffset(20, 40);
3039 window->setWindowTransform(0, 1, -1, 0);
3040
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003041 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003042
3043 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3044 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3045 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3046 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3047 MotionEvent* event = monitor.consumeMotion();
3048 // Even though window has transform, gesture monitor must not.
3049 ASSERT_EQ(ui::Transform(), event->getTransform());
3050}
3051
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003052TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003053 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003054 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003055
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003056 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003057 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003058 << "Injection should fail if there is a monitor, but no touchable window";
3059 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003060}
3061
chaviw81e2bb92019-12-18 15:03:51 -08003062TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003063 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08003064 sp<FakeWindowHandle> window =
3065 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3066
Arthur Hung72d8dc32020-03-28 00:48:39 +00003067 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003068
3069 NotifyMotionArgs motionArgs =
3070 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3071 ADISPLAY_ID_DEFAULT);
3072
3073 mDispatcher->notifyMotion(&motionArgs);
3074 // Window should receive motion down event.
3075 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3076
3077 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003078 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003079 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3080 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3081 motionArgs.pointerCoords[0].getX() - 10);
3082
3083 mDispatcher->notifyMotion(&motionArgs);
3084 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3085 0 /*expectedFlags*/);
3086}
3087
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003088/**
3089 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3090 * the device default right away. In the test scenario, we check both the default value,
3091 * and the action of enabling / disabling.
3092 */
3093TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003094 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003095 sp<FakeWindowHandle> window =
3096 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003097 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003098
3099 // Set focused application.
3100 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003101 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003102
3103 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003104 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003105 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003106 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3107
3108 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003109 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003110 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003111 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3112
3113 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003114 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3115 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003116 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003117 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003118 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003119 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003120 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3121
3122 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003123 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003124 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003125 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3126
3127 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003128 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3129 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003130 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003131 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003132 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003133 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003134 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3135
3136 window->assertNoEvents();
3137}
3138
Gang Wange9087892020-01-07 12:17:14 -05003139TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003140 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003141 sp<FakeWindowHandle> window =
3142 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3143
3144 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003145 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003146
Arthur Hung72d8dc32020-03-28 00:48:39 +00003147 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003148 setFocusedWindow(window);
3149
Gang Wange9087892020-01-07 12:17:14 -05003150 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3151
3152 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3153 mDispatcher->notifyKey(&keyArgs);
3154
3155 InputEvent* event = window->consume();
3156 ASSERT_NE(event, nullptr);
3157
3158 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3159 ASSERT_NE(verified, nullptr);
3160 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3161
3162 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3163 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3164 ASSERT_EQ(keyArgs.source, verified->source);
3165 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3166
3167 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3168
3169 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003170 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003171 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003172 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3173 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3174 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3175 ASSERT_EQ(0, verifiedKey.repeatCount);
3176}
3177
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003178TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003179 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003180 sp<FakeWindowHandle> window =
3181 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3182
3183 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3184
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003185 ui::Transform transform;
3186 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3187
3188 gui::DisplayInfo displayInfo;
3189 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3190 displayInfo.transform = transform;
3191
3192 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003193
3194 NotifyMotionArgs motionArgs =
3195 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3196 ADISPLAY_ID_DEFAULT);
3197 mDispatcher->notifyMotion(&motionArgs);
3198
3199 InputEvent* event = window->consume();
3200 ASSERT_NE(event, nullptr);
3201
3202 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3203 ASSERT_NE(verified, nullptr);
3204 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3205
3206 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3207 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3208 EXPECT_EQ(motionArgs.source, verified->source);
3209 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3210
3211 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3212
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003213 const vec2 rawXY =
3214 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3215 motionArgs.pointerCoords[0].getXYValue());
3216 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3217 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003218 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003219 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003220 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003221 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3222 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3223}
3224
chaviw09c8d2d2020-08-24 15:48:26 -07003225/**
3226 * Ensure that separate calls to sign the same data are generating the same key.
3227 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3228 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3229 * tests.
3230 */
3231TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3232 KeyEvent event = getTestKeyEvent();
3233 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3234
3235 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3236 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3237 ASSERT_EQ(hmac1, hmac2);
3238}
3239
3240/**
3241 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3242 */
3243TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3244 KeyEvent event = getTestKeyEvent();
3245 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3246 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3247
3248 verifiedEvent.deviceId += 1;
3249 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3250
3251 verifiedEvent.source += 1;
3252 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3253
3254 verifiedEvent.eventTimeNanos += 1;
3255 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3256
3257 verifiedEvent.displayId += 1;
3258 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3259
3260 verifiedEvent.action += 1;
3261 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3262
3263 verifiedEvent.downTimeNanos += 1;
3264 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3265
3266 verifiedEvent.flags += 1;
3267 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3268
3269 verifiedEvent.keyCode += 1;
3270 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3271
3272 verifiedEvent.scanCode += 1;
3273 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3274
3275 verifiedEvent.metaState += 1;
3276 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3277
3278 verifiedEvent.repeatCount += 1;
3279 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3280}
3281
Vishnu Nair958da932020-08-21 17:12:37 -07003282TEST_F(InputDispatcherTest, SetFocusedWindow) {
3283 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3284 sp<FakeWindowHandle> windowTop =
3285 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3286 sp<FakeWindowHandle> windowSecond =
3287 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3288 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3289
3290 // Top window is also focusable but is not granted focus.
3291 windowTop->setFocusable(true);
3292 windowSecond->setFocusable(true);
3293 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3294 setFocusedWindow(windowSecond);
3295
3296 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003297 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3298 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003299
3300 // Focused window should receive event.
3301 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3302 windowTop->assertNoEvents();
3303}
3304
3305TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3306 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3307 sp<FakeWindowHandle> window =
3308 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3309 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3310
3311 window->setFocusable(true);
3312 // Release channel for window is no longer valid.
3313 window->releaseChannel();
3314 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3315 setFocusedWindow(window);
3316
3317 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003318 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3319 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003320
3321 // window channel is invalid, so it should not receive any input event.
3322 window->assertNoEvents();
3323}
3324
3325TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3326 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3327 sp<FakeWindowHandle> window =
3328 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003329 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003330 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3331
Vishnu Nair958da932020-08-21 17:12:37 -07003332 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3333 setFocusedWindow(window);
3334
3335 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003336 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3337 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003338
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003339 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003340 window->assertNoEvents();
3341}
3342
3343TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3344 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3345 sp<FakeWindowHandle> windowTop =
3346 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3347 sp<FakeWindowHandle> windowSecond =
3348 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3349 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3350
3351 windowTop->setFocusable(true);
3352 windowSecond->setFocusable(true);
3353 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3354 setFocusedWindow(windowTop);
3355 windowTop->consumeFocusEvent(true);
3356
3357 setFocusedWindow(windowSecond, windowTop);
3358 windowSecond->consumeFocusEvent(true);
3359 windowTop->consumeFocusEvent(false);
3360
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003361 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3362 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003363
3364 // Focused window should receive event.
3365 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3366}
3367
3368TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3369 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3370 sp<FakeWindowHandle> windowTop =
3371 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3372 sp<FakeWindowHandle> windowSecond =
3373 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3374 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3375
3376 windowTop->setFocusable(true);
3377 windowSecond->setFocusable(true);
3378 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3379 setFocusedWindow(windowSecond, windowTop);
3380
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003381 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3382 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003383
3384 // Event should be dropped.
3385 windowTop->assertNoEvents();
3386 windowSecond->assertNoEvents();
3387}
3388
3389TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3390 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3391 sp<FakeWindowHandle> window =
3392 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3393 sp<FakeWindowHandle> previousFocusedWindow =
3394 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3395 ADISPLAY_ID_DEFAULT);
3396 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3397
3398 window->setFocusable(true);
3399 previousFocusedWindow->setFocusable(true);
3400 window->setVisible(false);
3401 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3402 setFocusedWindow(previousFocusedWindow);
3403 previousFocusedWindow->consumeFocusEvent(true);
3404
3405 // Requesting focus on invisible window takes focus from currently focused window.
3406 setFocusedWindow(window);
3407 previousFocusedWindow->consumeFocusEvent(false);
3408
3409 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003410 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003411 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003412 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003413
3414 // Window does not get focus event or key down.
3415 window->assertNoEvents();
3416
3417 // Window becomes visible.
3418 window->setVisible(true);
3419 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3420
3421 // Window receives focus event.
3422 window->consumeFocusEvent(true);
3423 // Focused window receives key down.
3424 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3425}
3426
Vishnu Nair599f1412021-06-21 10:39:58 -07003427TEST_F(InputDispatcherTest, DisplayRemoved) {
3428 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3429 sp<FakeWindowHandle> window =
3430 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3431 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3432
3433 // window is granted focus.
3434 window->setFocusable(true);
3435 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3436 setFocusedWindow(window);
3437 window->consumeFocusEvent(true);
3438
3439 // When a display is removed window loses focus.
3440 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3441 window->consumeFocusEvent(false);
3442}
3443
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003444/**
3445 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3446 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3447 * of the 'slipperyEnterWindow'.
3448 *
3449 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3450 * a way so that the touched location is no longer covered by the top window.
3451 *
3452 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3453 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3454 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3455 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3456 * with ACTION_DOWN).
3457 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3458 * window moved itself away from the touched location and had Flag::SLIPPERY.
3459 *
3460 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3461 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3462 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3463 *
3464 * In this test, we ensure that the event received by the bottom window has
3465 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3466 */
3467TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3468 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3469 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3470
3471 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3472 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3473
3474 sp<FakeWindowHandle> slipperyExitWindow =
3475 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003476 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003477 // Make sure this one overlaps the bottom window
3478 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3479 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3480 // one. Windows with the same owner are not considered to be occluding each other.
3481 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3482
3483 sp<FakeWindowHandle> slipperyEnterWindow =
3484 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3485 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3486
3487 mDispatcher->setInputWindows(
3488 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3489
3490 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3491 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3492 ADISPLAY_ID_DEFAULT, {{50, 50}});
3493 mDispatcher->notifyMotion(&args);
3494 slipperyExitWindow->consumeMotionDown();
3495 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3496 mDispatcher->setInputWindows(
3497 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3498
3499 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3500 ADISPLAY_ID_DEFAULT, {{51, 51}});
3501 mDispatcher->notifyMotion(&args);
3502
3503 slipperyExitWindow->consumeMotionCancel();
3504
3505 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3506 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3507}
3508
Garfield Tan1c7bc862020-01-28 13:24:04 -08003509class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3510protected:
3511 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3512 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3513
Chris Yea209fde2020-07-22 13:54:51 -07003514 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003515 sp<FakeWindowHandle> mWindow;
3516
3517 virtual void SetUp() override {
3518 mFakePolicy = new FakeInputDispatcherPolicy();
3519 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003520 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003521 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3522 ASSERT_EQ(OK, mDispatcher->start());
3523
3524 setUpWindow();
3525 }
3526
3527 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003528 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003529 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3530
Vishnu Nair47074b82020-08-14 11:54:47 -07003531 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003532 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003533 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003534 mWindow->consumeFocusEvent(true);
3535 }
3536
Chris Ye2ad95392020-09-01 13:44:44 -07003537 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003538 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003539 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003540 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3541 mDispatcher->notifyKey(&keyArgs);
3542
3543 // Window should receive key down event.
3544 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3545 }
3546
3547 void expectKeyRepeatOnce(int32_t repeatCount) {
3548 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3549 InputEvent* repeatEvent = mWindow->consume();
3550 ASSERT_NE(nullptr, repeatEvent);
3551
3552 uint32_t eventType = repeatEvent->getType();
3553 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3554
3555 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3556 uint32_t eventAction = repeatKeyEvent->getAction();
3557 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3558 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3559 }
3560
Chris Ye2ad95392020-09-01 13:44:44 -07003561 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003562 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003563 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003564 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3565 mDispatcher->notifyKey(&keyArgs);
3566
3567 // Window should receive key down event.
3568 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3569 0 /*expectedFlags*/);
3570 }
3571};
3572
3573TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003574 sendAndConsumeKeyDown(1 /* deviceId */);
3575 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3576 expectKeyRepeatOnce(repeatCount);
3577 }
3578}
3579
3580TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3581 sendAndConsumeKeyDown(1 /* deviceId */);
3582 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3583 expectKeyRepeatOnce(repeatCount);
3584 }
3585 sendAndConsumeKeyDown(2 /* deviceId */);
3586 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003587 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3588 expectKeyRepeatOnce(repeatCount);
3589 }
3590}
3591
3592TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003593 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003594 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003595 sendAndConsumeKeyUp(1 /* deviceId */);
3596 mWindow->assertNoEvents();
3597}
3598
3599TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3600 sendAndConsumeKeyDown(1 /* deviceId */);
3601 expectKeyRepeatOnce(1 /*repeatCount*/);
3602 sendAndConsumeKeyDown(2 /* deviceId */);
3603 expectKeyRepeatOnce(1 /*repeatCount*/);
3604 // Stale key up from device 1.
3605 sendAndConsumeKeyUp(1 /* deviceId */);
3606 // Device 2 is still down, keep repeating
3607 expectKeyRepeatOnce(2 /*repeatCount*/);
3608 expectKeyRepeatOnce(3 /*repeatCount*/);
3609 // Device 2 key up
3610 sendAndConsumeKeyUp(2 /* deviceId */);
3611 mWindow->assertNoEvents();
3612}
3613
3614TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3615 sendAndConsumeKeyDown(1 /* deviceId */);
3616 expectKeyRepeatOnce(1 /*repeatCount*/);
3617 sendAndConsumeKeyDown(2 /* deviceId */);
3618 expectKeyRepeatOnce(1 /*repeatCount*/);
3619 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3620 sendAndConsumeKeyUp(2 /* deviceId */);
3621 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003622 mWindow->assertNoEvents();
3623}
3624
liushenxiang42232912021-05-21 20:24:09 +08003625TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3626 sendAndConsumeKeyDown(DEVICE_ID);
3627 expectKeyRepeatOnce(1 /*repeatCount*/);
3628 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3629 mDispatcher->notifyDeviceReset(&args);
3630 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3631 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3632 mWindow->assertNoEvents();
3633}
3634
Garfield Tan1c7bc862020-01-28 13:24:04 -08003635TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003636 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003637 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3638 InputEvent* repeatEvent = mWindow->consume();
3639 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3640 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3641 IdGenerator::getSource(repeatEvent->getId()));
3642 }
3643}
3644
3645TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003646 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003647
3648 std::unordered_set<int32_t> idSet;
3649 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3650 InputEvent* repeatEvent = mWindow->consume();
3651 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3652 int32_t id = repeatEvent->getId();
3653 EXPECT_EQ(idSet.end(), idSet.find(id));
3654 idSet.insert(id);
3655 }
3656}
3657
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003658/* Test InputDispatcher for MultiDisplay */
3659class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3660public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003661 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003662 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003663
Chris Yea209fde2020-07-22 13:54:51 -07003664 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003665 windowInPrimary =
3666 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003667
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003668 // Set focus window for primary display, but focused display would be second one.
3669 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003670 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003672 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003673 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003674
Chris Yea209fde2020-07-22 13:54:51 -07003675 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003676 windowInSecondary =
3677 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003678 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003679 // Set focus display to second one.
3680 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3681 // Set focus window for second display.
3682 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003683 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003684 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003685 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003686 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003687 }
3688
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003689 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003690 InputDispatcherTest::TearDown();
3691
Chris Yea209fde2020-07-22 13:54:51 -07003692 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003693 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003694 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003695 windowInSecondary.clear();
3696 }
3697
3698protected:
Chris Yea209fde2020-07-22 13:54:51 -07003699 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003700 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003701 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003702 sp<FakeWindowHandle> windowInSecondary;
3703};
3704
3705TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3706 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003707 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3708 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3709 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003710 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003711 windowInSecondary->assertNoEvents();
3712
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003713 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003714 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3715 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3716 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003717 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003718 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003719}
3720
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003721TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003722 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003723 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3724 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003725 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003726 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003727 windowInSecondary->assertNoEvents();
3728
3729 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003730 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003731 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003732 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003733 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003734
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003735 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003736 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003737
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003738 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003739 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3740 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003741
3742 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003743 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003744 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003745 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003746 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003747 windowInSecondary->assertNoEvents();
3748}
3749
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003750// Test per-display input monitors for motion event.
3751TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003752 FakeMonitorReceiver monitorInPrimary =
3753 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3754 FakeMonitorReceiver monitorInSecondary =
3755 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003756
3757 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003758 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3759 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3760 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003761 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003762 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003763 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003764 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003765
3766 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003767 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3768 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3769 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003770 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003771 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003772 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003773 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003774
3775 // Test inject a non-pointer motion event.
3776 // If specific a display, it will dispatch to the focused window of particular display,
3777 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003778 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3779 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3780 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003781 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003782 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003783 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003784 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003785}
3786
3787// Test per-display input monitors for key event.
3788TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003789 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003790 FakeMonitorReceiver monitorInPrimary =
3791 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3792 FakeMonitorReceiver monitorInSecondary =
3793 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003794
3795 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003796 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3797 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003798 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003799 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003800 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003801 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003802}
3803
Vishnu Nair958da932020-08-21 17:12:37 -07003804TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3805 sp<FakeWindowHandle> secondWindowInPrimary =
3806 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3807 secondWindowInPrimary->setFocusable(true);
3808 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3809 setFocusedWindow(secondWindowInPrimary);
3810 windowInPrimary->consumeFocusEvent(false);
3811 secondWindowInPrimary->consumeFocusEvent(true);
3812
3813 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003814 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3815 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003816 windowInPrimary->assertNoEvents();
3817 windowInSecondary->assertNoEvents();
3818 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3819}
3820
Arthur Hungdfd528e2021-12-08 13:23:04 +00003821TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3822 FakeMonitorReceiver monitorInPrimary =
3823 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3824 FakeMonitorReceiver monitorInSecondary =
3825 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3826
3827 // Test touch down on primary display.
3828 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3829 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3830 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3831 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3832 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3833
3834 // Test touch down on second display.
3835 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3836 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3837 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3838 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3839 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3840
3841 // Trigger cancel touch.
3842 mDispatcher->cancelCurrentTouch();
3843 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3844 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3845 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3846 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3847
3848 // Test inject a move motion event, no window/monitor should receive the event.
3849 ASSERT_EQ(InputEventInjectionResult::FAILED,
3850 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3851 ADISPLAY_ID_DEFAULT, {110, 200}))
3852 << "Inject motion event should return InputEventInjectionResult::FAILED";
3853 windowInPrimary->assertNoEvents();
3854 monitorInPrimary.assertNoEvents();
3855
3856 ASSERT_EQ(InputEventInjectionResult::FAILED,
3857 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3858 SECOND_DISPLAY_ID, {110, 200}))
3859 << "Inject motion event should return InputEventInjectionResult::FAILED";
3860 windowInSecondary->assertNoEvents();
3861 monitorInSecondary.assertNoEvents();
3862}
3863
Jackal Guof9696682018-10-05 12:23:23 +08003864class InputFilterTest : public InputDispatcherTest {
3865protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003866 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3867 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003868 NotifyMotionArgs motionArgs;
3869
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003870 motionArgs =
3871 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003872 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003873 motionArgs =
3874 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003875 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003876 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003877 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003878 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3879 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003880 } else {
3881 mFakePolicy->assertFilterInputEventWasNotCalled();
3882 }
3883 }
3884
3885 void testNotifyKey(bool expectToBeFiltered) {
3886 NotifyKeyArgs keyArgs;
3887
3888 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3889 mDispatcher->notifyKey(&keyArgs);
3890 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3891 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003892 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003893
3894 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003895 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003896 } else {
3897 mFakePolicy->assertFilterInputEventWasNotCalled();
3898 }
3899 }
3900};
3901
3902// Test InputFilter for MotionEvent
3903TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3904 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3905 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3906 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3907
3908 // Enable InputFilter
3909 mDispatcher->setInputFilterEnabled(true);
3910 // Test touch on both primary and second display, and check if both events are filtered.
3911 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3912 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3913
3914 // Disable InputFilter
3915 mDispatcher->setInputFilterEnabled(false);
3916 // Test touch on both primary and second display, and check if both events aren't filtered.
3917 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3918 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3919}
3920
3921// Test InputFilter for KeyEvent
3922TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3923 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3924 testNotifyKey(/*expectToBeFiltered*/ false);
3925
3926 // Enable InputFilter
3927 mDispatcher->setInputFilterEnabled(true);
3928 // Send a key event, and check if it is filtered.
3929 testNotifyKey(/*expectToBeFiltered*/ true);
3930
3931 // Disable InputFilter
3932 mDispatcher->setInputFilterEnabled(false);
3933 // Send a key event, and check if it isn't filtered.
3934 testNotifyKey(/*expectToBeFiltered*/ false);
3935}
3936
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003937// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3938// logical display coordinate space.
3939TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3940 ui::Transform firstDisplayTransform;
3941 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3942 ui::Transform secondDisplayTransform;
3943 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3944
3945 std::vector<gui::DisplayInfo> displayInfos(2);
3946 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3947 displayInfos[0].transform = firstDisplayTransform;
3948 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3949 displayInfos[1].transform = secondDisplayTransform;
3950
3951 mDispatcher->onWindowInfosChanged({}, displayInfos);
3952
3953 // Enable InputFilter
3954 mDispatcher->setInputFilterEnabled(true);
3955
3956 // Ensure the correct transforms are used for the displays.
3957 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3958 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3959}
3960
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003961class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3962protected:
3963 virtual void SetUp() override {
3964 InputDispatcherTest::SetUp();
3965
3966 /**
3967 * We don't need to enable input filter to test the injected event policy, but we enabled it
3968 * here to make the tests more realistic, since this policy only matters when inputfilter is
3969 * on.
3970 */
3971 mDispatcher->setInputFilterEnabled(true);
3972
3973 std::shared_ptr<InputApplicationHandle> application =
3974 std::make_shared<FakeApplicationHandle>();
3975 mWindow =
3976 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3977
3978 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3979 mWindow->setFocusable(true);
3980 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3981 setFocusedWindow(mWindow);
3982 mWindow->consumeFocusEvent(true);
3983 }
3984
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003985 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3986 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003987 KeyEvent event;
3988
3989 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3990 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3991 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3992 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3993 const int32_t additionalPolicyFlags =
3994 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3995 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3996 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3997 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3998 policyFlags | additionalPolicyFlags));
3999
4000 InputEvent* received = mWindow->consume();
4001 ASSERT_NE(nullptr, received);
4002 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004003 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4004 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4005 ASSERT_EQ(flags, keyEvent.getFlags());
4006 }
4007
4008 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4009 int32_t flags) {
4010 MotionEvent event;
4011 PointerProperties pointerProperties[1];
4012 PointerCoords pointerCoords[1];
4013 pointerProperties[0].clear();
4014 pointerProperties[0].id = 0;
4015 pointerCoords[0].clear();
4016 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4017 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4018
4019 ui::Transform identityTransform;
4020 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4021 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4022 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4023 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4024 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004025 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004026 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004027 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4028
4029 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4030 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4031 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
4032 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4033 policyFlags | additionalPolicyFlags));
4034
4035 InputEvent* received = mWindow->consume();
4036 ASSERT_NE(nullptr, received);
4037 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4038 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4039 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4040 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004041 }
4042
4043private:
4044 sp<FakeWindowHandle> mWindow;
4045};
4046
4047TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004048 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4049 // filter. Without it, the event will no different from a regularly injected event, and the
4050 // injected device id will be overwritten.
4051 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4052 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004053}
4054
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004055TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004056 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004057 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4058 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4059}
4060
4061TEST_F(InputFilterInjectionPolicyTest,
4062 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4063 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4064 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4065 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004066}
4067
4068TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4069 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004070 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004071}
4072
chaviwfd6d3512019-03-25 13:23:49 -07004073class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004074 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004075 InputDispatcherTest::SetUp();
4076
Chris Yea209fde2020-07-22 13:54:51 -07004077 std::shared_ptr<FakeApplicationHandle> application =
4078 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004079 mUnfocusedWindow =
4080 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004081 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004082
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004083 mFocusedWindow =
4084 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4085 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004086
4087 // Set focused application.
4088 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004089 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004090
4091 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004092 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004093 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004094 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004095 }
4096
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004097 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004098 InputDispatcherTest::TearDown();
4099
4100 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004101 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004102 }
4103
4104protected:
4105 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004106 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004107 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004108};
4109
4110// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4111// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4112// the onPointerDownOutsideFocus callback.
4113TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004114 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004115 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4116 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004117 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004118 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004119
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004120 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004121 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4122}
4123
4124// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4125// DOWN on the window that doesn't have focus. Ensure no window received the
4126// onPointerDownOutsideFocus callback.
4127TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004128 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004129 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004130 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004131 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004132
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004133 ASSERT_TRUE(mDispatcher->waitForIdle());
4134 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004135}
4136
4137// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4138// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4139TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004140 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4141 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004142 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004143 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004144
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004145 ASSERT_TRUE(mDispatcher->waitForIdle());
4146 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004147}
4148
4149// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4150// DOWN on the window that already has focus. Ensure no window received the
4151// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004152TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004153 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004154 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004155 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004156 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004157 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004158
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004159 ASSERT_TRUE(mDispatcher->waitForIdle());
4160 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004161}
4162
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004163// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4164// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4165TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4166 const MotionEvent event =
4167 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4168 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4169 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4170 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4171 .build();
4172 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4173 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4174 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4175
4176 ASSERT_TRUE(mDispatcher->waitForIdle());
4177 mFakePolicy->assertOnPointerDownWasNotCalled();
4178 // Ensure that the unfocused window did not receive any FOCUS events.
4179 mUnfocusedWindow->assertNoEvents();
4180}
4181
chaviwaf87b3e2019-10-01 16:59:28 -07004182// These tests ensures we can send touch events to a single client when there are multiple input
4183// windows that point to the same client token.
4184class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4185 virtual void SetUp() override {
4186 InputDispatcherTest::SetUp();
4187
Chris Yea209fde2020-07-22 13:54:51 -07004188 std::shared_ptr<FakeApplicationHandle> application =
4189 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004190 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4191 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004192 mWindow1->setFrame(Rect(0, 0, 100, 100));
4193
4194 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4195 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004196 mWindow2->setFrame(Rect(100, 100, 200, 200));
4197
Arthur Hung72d8dc32020-03-28 00:48:39 +00004198 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004199 }
4200
4201protected:
4202 sp<FakeWindowHandle> mWindow1;
4203 sp<FakeWindowHandle> mWindow2;
4204
4205 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004206 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004207 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4208 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004209 }
4210
4211 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4212 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004213 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004214 InputEvent* event = window->consume();
4215
4216 ASSERT_NE(nullptr, event) << name.c_str()
4217 << ": consumer should have returned non-NULL event.";
4218
4219 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4220 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4221 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4222
4223 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004224 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004225
4226 for (size_t i = 0; i < points.size(); i++) {
4227 float expectedX = points[i].x;
4228 float expectedY = points[i].y;
4229
4230 EXPECT_EQ(expectedX, motionEvent.getX(i))
4231 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4232 << ", got " << motionEvent.getX(i);
4233 EXPECT_EQ(expectedY, motionEvent.getY(i))
4234 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4235 << ", got " << motionEvent.getY(i);
4236 }
4237 }
chaviw9eaa22c2020-07-01 16:21:27 -07004238
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004239 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004240 std::vector<PointF> expectedPoints) {
4241 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4242 ADISPLAY_ID_DEFAULT, touchedPoints);
4243 mDispatcher->notifyMotion(&motionArgs);
4244
4245 // Always consume from window1 since it's the window that has the InputReceiver
4246 consumeMotionEvent(mWindow1, action, expectedPoints);
4247 }
chaviwaf87b3e2019-10-01 16:59:28 -07004248};
4249
4250TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4251 // Touch Window 1
4252 PointF touchedPoint = {10, 10};
4253 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004254 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004255
4256 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004257 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004258
4259 // Touch Window 2
4260 touchedPoint = {150, 150};
4261 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004262 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004263}
4264
chaviw9eaa22c2020-07-01 16:21:27 -07004265TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4266 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004267 mWindow2->setWindowScale(0.5f, 0.5f);
4268
4269 // Touch Window 1
4270 PointF touchedPoint = {10, 10};
4271 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004272 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004273 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004274 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004275
4276 // Touch Window 2
4277 touchedPoint = {150, 150};
4278 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004279 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4280 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004281
chaviw9eaa22c2020-07-01 16:21:27 -07004282 // Update the transform so rotation is set
4283 mWindow2->setWindowTransform(0, -1, 1, 0);
4284 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4285 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004286}
4287
chaviw9eaa22c2020-07-01 16:21:27 -07004288TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004289 mWindow2->setWindowScale(0.5f, 0.5f);
4290
4291 // Touch Window 1
4292 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4293 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004294 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004295
4296 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004297 touchedPoints.push_back(PointF{150, 150});
4298 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004299 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004300
chaviw9eaa22c2020-07-01 16:21:27 -07004301 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004302 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004303 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004304
chaviw9eaa22c2020-07-01 16:21:27 -07004305 // Update the transform so rotation is set for Window 2
4306 mWindow2->setWindowTransform(0, -1, 1, 0);
4307 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004308 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004309}
4310
chaviw9eaa22c2020-07-01 16:21:27 -07004311TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004312 mWindow2->setWindowScale(0.5f, 0.5f);
4313
4314 // Touch Window 1
4315 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4316 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004317 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004318
4319 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004320 touchedPoints.push_back(PointF{150, 150});
4321 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004322
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004323 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004324
4325 // Move both windows
4326 touchedPoints = {{20, 20}, {175, 175}};
4327 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4328 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4329
chaviw9eaa22c2020-07-01 16:21:27 -07004330 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004331
chaviw9eaa22c2020-07-01 16:21:27 -07004332 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004333 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004334 expectedPoints.pop_back();
4335
4336 // Touch Window 2
4337 mWindow2->setWindowTransform(0, -1, 1, 0);
4338 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004339 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004340
4341 // Move both windows
4342 touchedPoints = {{20, 20}, {175, 175}};
4343 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4344 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4345
4346 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004347}
4348
4349TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4350 mWindow1->setWindowScale(0.5f, 0.5f);
4351
4352 // Touch Window 1
4353 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4354 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004355 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004356
4357 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004358 touchedPoints.push_back(PointF{150, 150});
4359 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004360
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004361 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004362
4363 // Move both windows
4364 touchedPoints = {{20, 20}, {175, 175}};
4365 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4366 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4367
chaviw9eaa22c2020-07-01 16:21:27 -07004368 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004369}
4370
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004371class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4372 virtual void SetUp() override {
4373 InputDispatcherTest::SetUp();
4374
Chris Yea209fde2020-07-22 13:54:51 -07004375 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004376 mApplication->setDispatchingTimeout(20ms);
4377 mWindow =
4378 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4379 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004380 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004381 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004382
4383 // Set focused application.
4384 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4385
4386 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004387 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004388 mWindow->consumeFocusEvent(true);
4389 }
4390
4391 virtual void TearDown() override {
4392 InputDispatcherTest::TearDown();
4393 mWindow.clear();
4394 }
4395
4396protected:
Chris Yea209fde2020-07-22 13:54:51 -07004397 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004398 sp<FakeWindowHandle> mWindow;
4399 static constexpr PointF WINDOW_LOCATION = {20, 20};
4400
4401 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004402 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004403 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4404 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004405 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004406 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4407 WINDOW_LOCATION));
4408 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004409
4410 sp<FakeWindowHandle> addSpyWindow() {
4411 sp<FakeWindowHandle> spy =
4412 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4413 spy->setTrustedOverlay(true);
4414 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004415 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004416 spy->setDispatchingTimeout(30ms);
4417 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4418 return spy;
4419 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004420};
4421
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004422// Send a tap and respond, which should not cause an ANR.
4423TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4424 tapOnWindow();
4425 mWindow->consumeMotionDown();
4426 mWindow->consumeMotionUp();
4427 ASSERT_TRUE(mDispatcher->waitForIdle());
4428 mFakePolicy->assertNotifyAnrWasNotCalled();
4429}
4430
4431// Send a regular key and respond, which should not cause an ANR.
4432TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004433 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004434 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4435 ASSERT_TRUE(mDispatcher->waitForIdle());
4436 mFakePolicy->assertNotifyAnrWasNotCalled();
4437}
4438
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004439TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4440 mWindow->setFocusable(false);
4441 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4442 mWindow->consumeFocusEvent(false);
4443
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004444 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004445 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004446 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4447 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004448 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004449 // Key will not go to window because we have no focused window.
4450 // The 'no focused window' ANR timer should start instead.
4451
4452 // Now, the focused application goes away.
4453 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4454 // The key should get dropped and there should be no ANR.
4455
4456 ASSERT_TRUE(mDispatcher->waitForIdle());
4457 mFakePolicy->assertNotifyAnrWasNotCalled();
4458}
4459
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004460// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004461// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4462// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004463TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004464 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004465 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4466 WINDOW_LOCATION));
4467
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004468 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4469 ASSERT_TRUE(sequenceNum);
4470 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004471 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004472
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004473 mWindow->finishEvent(*sequenceNum);
4474 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4475 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004476 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004477 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004478}
4479
4480// Send a key to the app and have the app not respond right away.
4481TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4482 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004483 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004484 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4485 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004486 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004487 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004488 ASSERT_TRUE(mDispatcher->waitForIdle());
4489}
4490
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004491// We have a focused application, but no focused window
4492TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004493 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004494 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4495 mWindow->consumeFocusEvent(false);
4496
4497 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004498 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004499 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4500 WINDOW_LOCATION));
4501 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4502 mDispatcher->waitForIdle();
4503 mFakePolicy->assertNotifyAnrWasNotCalled();
4504
4505 // Once a focused event arrives, we get an ANR for this application
4506 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4507 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004508 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004509 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004510 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004511 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004512 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004513 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004514 ASSERT_TRUE(mDispatcher->waitForIdle());
4515}
4516
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004517/**
4518 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4519 * there will not be an ANR.
4520 */
4521TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4522 mWindow->setFocusable(false);
4523 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4524 mWindow->consumeFocusEvent(false);
4525
4526 KeyEvent event;
4527 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4528 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4529
4530 // Define a valid key down event that is stale (too old).
4531 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4532 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4533 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4534
4535 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4536
4537 InputEventInjectionResult result =
4538 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
4539 InputEventInjectionSync::WAIT_FOR_RESULT,
4540 INJECT_EVENT_TIMEOUT, policyFlags);
4541 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4542 << "Injection should fail because the event is stale";
4543
4544 ASSERT_TRUE(mDispatcher->waitForIdle());
4545 mFakePolicy->assertNotifyAnrWasNotCalled();
4546 mWindow->assertNoEvents();
4547}
4548
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004549// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004550// Make sure that we don't notify policy twice about the same ANR.
4551TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
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);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004555
4556 // Once a focused event arrives, we get an ANR for this application
4557 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4558 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004559 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004560 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004561 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004562 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004563 const std::chrono::duration appTimeout =
4564 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004565 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004566
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004567 std::this_thread::sleep_for(appTimeout);
4568 // ANR should not be raised again. It is up to policy to do that if it desires.
4569 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004570
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004571 // If we now get a focused window, the ANR should stop, but the policy handles that via
4572 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004573 ASSERT_TRUE(mDispatcher->waitForIdle());
4574}
4575
4576// We have a focused application, but no focused window
4577TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004578 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004579 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4580 mWindow->consumeFocusEvent(false);
4581
4582 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004583 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004584 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004585 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4586 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004587
4588 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004589 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004590
4591 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004592 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004593 ASSERT_TRUE(mDispatcher->waitForIdle());
4594 mWindow->assertNoEvents();
4595}
4596
4597/**
4598 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4599 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4600 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4601 * the ANR mechanism should still work.
4602 *
4603 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4604 * DOWN event, while not responding on the second one.
4605 */
4606TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4607 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4608 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4609 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4610 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4611 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004612 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004613
4614 // Now send ACTION_UP, with identical timestamp
4615 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4616 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4617 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4618 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004619 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004620
4621 // We have now sent down and up. Let's consume first event and then ANR on the second.
4622 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4623 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004624 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004625}
4626
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004627// A spy window can receive an ANR
4628TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4629 sp<FakeWindowHandle> spy = addSpyWindow();
4630
4631 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4632 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4633 WINDOW_LOCATION));
4634 mWindow->consumeMotionDown();
4635
4636 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4637 ASSERT_TRUE(sequenceNum);
4638 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004639 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004640
4641 spy->finishEvent(*sequenceNum);
4642 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4643 0 /*flags*/);
4644 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004645 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004646}
4647
4648// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004649// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004650TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4651 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004652
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004653 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4654 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004655 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004656 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004657
4658 // Stuck on the ACTION_UP
4659 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004660 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004661
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004662 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004663 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004664 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4665 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004666
4667 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4668 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004669 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004670 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004671 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004672}
4673
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004674// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004675// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004676TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4677 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004678
4679 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004680 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4681 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004682
4683 mWindow->consumeMotionDown();
4684 // Stuck on the ACTION_UP
4685 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004686 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004687
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004688 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004689 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004690 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4691 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004692
4693 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4694 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004695 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004696 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004697 spy->assertNoEvents();
4698}
4699
4700TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4701 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4702
4703 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4704
4705 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4706 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4707 WINDOW_LOCATION));
4708
4709 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4710 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4711 ASSERT_TRUE(consumeSeq);
4712
Prabir Pradhanedd96402022-02-15 01:46:16 -08004713 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004714
4715 monitor.finishEvent(*consumeSeq);
4716 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4717
4718 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004719 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004720}
4721
4722// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4723// process events, you don't get an anr. When the window later becomes unresponsive again, you
4724// get an ANR again.
4725// 1. tap -> block on ACTION_UP -> receive ANR
4726// 2. consume all pending events (= queue becomes healthy again)
4727// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4728TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4729 tapOnWindow();
4730
4731 mWindow->consumeMotionDown();
4732 // Block on ACTION_UP
4733 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004734 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004735 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4736 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004737 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004738 mWindow->assertNoEvents();
4739
4740 tapOnWindow();
4741 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004742 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004743 mWindow->consumeMotionUp();
4744
4745 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004746 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004747 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004748 mWindow->assertNoEvents();
4749}
4750
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004751// If a connection remains unresponsive for a while, make sure policy is only notified once about
4752// it.
4753TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004754 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004755 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4756 WINDOW_LOCATION));
4757
4758 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004759 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004760 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004761 // 'notifyConnectionUnresponsive' should only be called once per connection
4762 mFakePolicy->assertNotifyAnrWasNotCalled();
4763 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004764 mWindow->consumeMotionDown();
4765 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4766 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4767 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004768 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004769 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004770 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004771}
4772
4773/**
4774 * If a window is processing a motion event, and then a key event comes in, the key event should
4775 * not to to the focused window until the motion is processed.
4776 *
4777 * Warning!!!
4778 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4779 * and the injection timeout that we specify when injecting the key.
4780 * We must have the injection timeout (10ms) be smaller than
4781 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4782 *
4783 * If that value changes, this test should also change.
4784 */
4785TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4786 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4787 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4788
4789 tapOnWindow();
4790 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4791 ASSERT_TRUE(downSequenceNum);
4792 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4793 ASSERT_TRUE(upSequenceNum);
4794 // Don't finish the events yet, and send a key
4795 // Injection will "succeed" because we will eventually give up and send the key to the focused
4796 // window even if motions are still being processed. But because the injection timeout is short,
4797 // we will receive INJECTION_TIMED_OUT as the result.
4798
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004799 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004800 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004801 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4802 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004803 // Key will not be sent to the window, yet, because the window is still processing events
4804 // and the key remains pending, waiting for the touch events to be processed
4805 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4806 ASSERT_FALSE(keySequenceNum);
4807
4808 std::this_thread::sleep_for(500ms);
4809 // if we wait long enough though, dispatcher will give up, and still send the key
4810 // to the focused window, even though we have not yet finished the motion event
4811 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4812 mWindow->finishEvent(*downSequenceNum);
4813 mWindow->finishEvent(*upSequenceNum);
4814}
4815
4816/**
4817 * If a window is processing a motion event, and then a key event comes in, the key event should
4818 * not go to the focused window until the motion is processed.
4819 * If then a new motion comes in, then the pending key event should be going to the currently
4820 * focused window right away.
4821 */
4822TEST_F(InputDispatcherSingleWindowAnr,
4823 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4824 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4825 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4826
4827 tapOnWindow();
4828 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4829 ASSERT_TRUE(downSequenceNum);
4830 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4831 ASSERT_TRUE(upSequenceNum);
4832 // Don't finish the events yet, and send a key
4833 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004834 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004835 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004836 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004837 // At this point, key is still pending, and should not be sent to the application yet.
4838 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4839 ASSERT_FALSE(keySequenceNum);
4840
4841 // Now tap down again. It should cause the pending key to go to the focused window right away.
4842 tapOnWindow();
4843 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4844 // the other events yet. We can finish events in any order.
4845 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4846 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4847 mWindow->consumeMotionDown();
4848 mWindow->consumeMotionUp();
4849 mWindow->assertNoEvents();
4850}
4851
4852class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4853 virtual void SetUp() override {
4854 InputDispatcherTest::SetUp();
4855
Chris Yea209fde2020-07-22 13:54:51 -07004856 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004857 mApplication->setDispatchingTimeout(10ms);
4858 mUnfocusedWindow =
4859 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4860 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004861 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004862 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004863
4864 mFocusedWindow =
4865 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004866 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004867 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004868
4869 // Set focused application.
4870 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004871 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004872
4873 // Expect one focus window exist in display.
4874 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004875 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004876 mFocusedWindow->consumeFocusEvent(true);
4877 }
4878
4879 virtual void TearDown() override {
4880 InputDispatcherTest::TearDown();
4881
4882 mUnfocusedWindow.clear();
4883 mFocusedWindow.clear();
4884 }
4885
4886protected:
Chris Yea209fde2020-07-22 13:54:51 -07004887 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004888 sp<FakeWindowHandle> mUnfocusedWindow;
4889 sp<FakeWindowHandle> mFocusedWindow;
4890 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4891 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4892 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4893
4894 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4895
4896 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4897
4898private:
4899 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004900 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004901 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4902 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004903 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004904 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4905 location));
4906 }
4907};
4908
4909// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4910// should be ANR'd first.
4911TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004912 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004913 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4914 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004915 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004916 mFocusedWindow->consumeMotionDown();
4917 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4918 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4919 // We consumed all events, so no ANR
4920 ASSERT_TRUE(mDispatcher->waitForIdle());
4921 mFakePolicy->assertNotifyAnrWasNotCalled();
4922
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004923 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004924 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4925 FOCUSED_WINDOW_LOCATION));
4926 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4927 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004928
4929 const std::chrono::duration timeout =
4930 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004931 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004932 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4933 // sequence to make it consistent
4934 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004935 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004936 mFocusedWindow->consumeMotionDown();
4937 // This cancel is generated because the connection was unresponsive
4938 mFocusedWindow->consumeMotionCancel();
4939 mFocusedWindow->assertNoEvents();
4940 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004941 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004942 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
4943 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004944 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004945}
4946
4947// If we have 2 windows with identical timeouts that are both unresponsive,
4948// it doesn't matter which order they should have ANR.
4949// But we should receive ANR for both.
4950TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4951 // Set the timeout for unfocused window to match the focused window
4952 mUnfocusedWindow->setDispatchingTimeout(10ms);
4953 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4954
4955 tapOnFocusedWindow();
4956 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08004957 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
4958 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
4959 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004960
4961 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004962 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4963 mFocusedWindow->getToken() == anrConnectionToken2);
4964 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4965 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004966
4967 ASSERT_TRUE(mDispatcher->waitForIdle());
4968 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004969
4970 mFocusedWindow->consumeMotionDown();
4971 mFocusedWindow->consumeMotionUp();
4972 mUnfocusedWindow->consumeMotionOutside();
4973
Prabir Pradhanedd96402022-02-15 01:46:16 -08004974 sp<IBinder> responsiveToken1, responsiveToken2;
4975 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
4976 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004977
4978 // Both applications should be marked as responsive, in any order
4979 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4980 mFocusedWindow->getToken() == responsiveToken2);
4981 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4982 mUnfocusedWindow->getToken() == responsiveToken2);
4983 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004984}
4985
4986// If a window is already not responding, the second tap on the same window should be ignored.
4987// We should also log an error to account for the dropped event (not tested here).
4988// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4989TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4990 tapOnFocusedWindow();
4991 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4992 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4993 // Receive the events, but don't respond
4994 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4995 ASSERT_TRUE(downEventSequenceNum);
4996 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4997 ASSERT_TRUE(upEventSequenceNum);
4998 const std::chrono::duration timeout =
4999 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005000 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005001
5002 // Tap once again
5003 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005004 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005005 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5006 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005007 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005008 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5009 FOCUSED_WINDOW_LOCATION));
5010 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5011 // valid touch target
5012 mUnfocusedWindow->assertNoEvents();
5013
5014 // Consume the first tap
5015 mFocusedWindow->finishEvent(*downEventSequenceNum);
5016 mFocusedWindow->finishEvent(*upEventSequenceNum);
5017 ASSERT_TRUE(mDispatcher->waitForIdle());
5018 // The second tap did not go to the focused window
5019 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005020 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005021 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5022 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005023 mFakePolicy->assertNotifyAnrWasNotCalled();
5024}
5025
5026// If you tap outside of all windows, there will not be ANR
5027TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005028 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005029 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5030 LOCATION_OUTSIDE_ALL_WINDOWS));
5031 ASSERT_TRUE(mDispatcher->waitForIdle());
5032 mFakePolicy->assertNotifyAnrWasNotCalled();
5033}
5034
5035// Since the focused window is paused, tapping on it should not produce any events
5036TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5037 mFocusedWindow->setPaused(true);
5038 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5039
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005040 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005041 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5042 FOCUSED_WINDOW_LOCATION));
5043
5044 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5045 ASSERT_TRUE(mDispatcher->waitForIdle());
5046 // Should not ANR because the window is paused, and touches shouldn't go to it
5047 mFakePolicy->assertNotifyAnrWasNotCalled();
5048
5049 mFocusedWindow->assertNoEvents();
5050 mUnfocusedWindow->assertNoEvents();
5051}
5052
5053/**
5054 * If a window is processing a motion event, and then a key event comes in, the key event should
5055 * not to to the focused window until the motion is processed.
5056 * If a different window becomes focused at this time, the key should go to that window instead.
5057 *
5058 * Warning!!!
5059 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5060 * and the injection timeout that we specify when injecting the key.
5061 * We must have the injection timeout (10ms) be smaller than
5062 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5063 *
5064 * If that value changes, this test should also change.
5065 */
5066TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5067 // Set a long ANR timeout to prevent it from triggering
5068 mFocusedWindow->setDispatchingTimeout(2s);
5069 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5070
5071 tapOnUnfocusedWindow();
5072 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5073 ASSERT_TRUE(downSequenceNum);
5074 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5075 ASSERT_TRUE(upSequenceNum);
5076 // Don't finish the events yet, and send a key
5077 // Injection will succeed because we will eventually give up and send the key to the focused
5078 // window even if motions are still being processed.
5079
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005080 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005081 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005082 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5083 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005084 // Key will not be sent to the window, yet, because the window is still processing events
5085 // and the key remains pending, waiting for the touch events to be processed
5086 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5087 ASSERT_FALSE(keySequenceNum);
5088
5089 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005090 mFocusedWindow->setFocusable(false);
5091 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005092 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005093 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005094
5095 // Focus events should precede the key events
5096 mUnfocusedWindow->consumeFocusEvent(true);
5097 mFocusedWindow->consumeFocusEvent(false);
5098
5099 // Finish the tap events, which should unblock dispatcher
5100 mUnfocusedWindow->finishEvent(*downSequenceNum);
5101 mUnfocusedWindow->finishEvent(*upSequenceNum);
5102
5103 // Now that all queues are cleared and no backlog in the connections, the key event
5104 // can finally go to the newly focused "mUnfocusedWindow".
5105 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5106 mFocusedWindow->assertNoEvents();
5107 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005108 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005109}
5110
5111// When the touch stream is split across 2 windows, and one of them does not respond,
5112// then ANR should be raised and the touch should be canceled for the unresponsive window.
5113// The other window should not be affected by that.
5114TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5115 // Touch Window 1
5116 NotifyMotionArgs motionArgs =
5117 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5118 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5119 mDispatcher->notifyMotion(&motionArgs);
5120 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5121 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5122
5123 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005124 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5125 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005126 mDispatcher->notifyMotion(&motionArgs);
5127
5128 const std::chrono::duration timeout =
5129 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005130 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005131
5132 mUnfocusedWindow->consumeMotionDown();
5133 mFocusedWindow->consumeMotionDown();
5134 // Focused window may or may not receive ACTION_MOVE
5135 // But it should definitely receive ACTION_CANCEL due to the ANR
5136 InputEvent* event;
5137 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5138 ASSERT_TRUE(moveOrCancelSequenceNum);
5139 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5140 ASSERT_NE(nullptr, event);
5141 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5142 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5143 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5144 mFocusedWindow->consumeMotionCancel();
5145 } else {
5146 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5147 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005148 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005149 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5150 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005151
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005152 mUnfocusedWindow->assertNoEvents();
5153 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005154 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005155}
5156
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005157/**
5158 * If we have no focused window, and a key comes in, we start the ANR timer.
5159 * The focused application should add a focused window before the timer runs out to prevent ANR.
5160 *
5161 * If the user touches another application during this time, the key should be dropped.
5162 * Next, if a new focused window comes in, without toggling the focused application,
5163 * then no ANR should occur.
5164 *
5165 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5166 * but in some cases the policy may not update the focused application.
5167 */
5168TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5169 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5170 std::make_shared<FakeApplicationHandle>();
5171 focusedApplication->setDispatchingTimeout(60ms);
5172 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5173 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5174 mFocusedWindow->setFocusable(false);
5175
5176 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5177 mFocusedWindow->consumeFocusEvent(false);
5178
5179 // Send a key. The ANR timer should start because there is no focused window.
5180 // 'focusedApplication' will get blamed if this timer completes.
5181 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005182 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005183 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005184 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5185 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005186 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005187
5188 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5189 // then the injected touches won't cause the focused event to get dropped.
5190 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5191 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5192 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5193 // For this test, it means that the key would get delivered to the window once it becomes
5194 // focused.
5195 std::this_thread::sleep_for(10ms);
5196
5197 // Touch unfocused window. This should force the pending key to get dropped.
5198 NotifyMotionArgs motionArgs =
5199 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5200 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5201 mDispatcher->notifyMotion(&motionArgs);
5202
5203 // We do not consume the motion right away, because that would require dispatcher to first
5204 // process (== drop) the key event, and by that time, ANR will be raised.
5205 // Set the focused window first.
5206 mFocusedWindow->setFocusable(true);
5207 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5208 setFocusedWindow(mFocusedWindow);
5209 mFocusedWindow->consumeFocusEvent(true);
5210 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5211 // to another application. This could be a bug / behaviour in the policy.
5212
5213 mUnfocusedWindow->consumeMotionDown();
5214
5215 ASSERT_TRUE(mDispatcher->waitForIdle());
5216 // Should not ANR because we actually have a focused window. It was just added too slowly.
5217 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5218}
5219
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005220// These tests ensure we cannot send touch events to a window that's positioned behind a window
5221// that has feature NO_INPUT_CHANNEL.
5222// Layout:
5223// Top (closest to user)
5224// mNoInputWindow (above all windows)
5225// mBottomWindow
5226// Bottom (furthest from user)
5227class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5228 virtual void SetUp() override {
5229 InputDispatcherTest::SetUp();
5230
5231 mApplication = std::make_shared<FakeApplicationHandle>();
5232 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5233 "Window without input channel", ADISPLAY_ID_DEFAULT,
5234 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5235
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005236 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005237 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5238 // It's perfectly valid for this window to not have an associated input channel
5239
5240 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5241 ADISPLAY_ID_DEFAULT);
5242 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5243
5244 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5245 }
5246
5247protected:
5248 std::shared_ptr<FakeApplicationHandle> mApplication;
5249 sp<FakeWindowHandle> mNoInputWindow;
5250 sp<FakeWindowHandle> mBottomWindow;
5251};
5252
5253TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5254 PointF touchedPoint = {10, 10};
5255
5256 NotifyMotionArgs motionArgs =
5257 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5258 ADISPLAY_ID_DEFAULT, {touchedPoint});
5259 mDispatcher->notifyMotion(&motionArgs);
5260
5261 mNoInputWindow->assertNoEvents();
5262 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5263 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5264 // and therefore should prevent mBottomWindow from receiving touches
5265 mBottomWindow->assertNoEvents();
5266}
5267
5268/**
5269 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5270 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5271 */
5272TEST_F(InputDispatcherMultiWindowOcclusionTests,
5273 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5274 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5275 "Window with input channel and NO_INPUT_CHANNEL",
5276 ADISPLAY_ID_DEFAULT);
5277
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005278 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005279 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5280 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5281
5282 PointF touchedPoint = {10, 10};
5283
5284 NotifyMotionArgs motionArgs =
5285 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5286 ADISPLAY_ID_DEFAULT, {touchedPoint});
5287 mDispatcher->notifyMotion(&motionArgs);
5288
5289 mNoInputWindow->assertNoEvents();
5290 mBottomWindow->assertNoEvents();
5291}
5292
Vishnu Nair958da932020-08-21 17:12:37 -07005293class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5294protected:
5295 std::shared_ptr<FakeApplicationHandle> mApp;
5296 sp<FakeWindowHandle> mWindow;
5297 sp<FakeWindowHandle> mMirror;
5298
5299 virtual void SetUp() override {
5300 InputDispatcherTest::SetUp();
5301 mApp = std::make_shared<FakeApplicationHandle>();
5302 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5303 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5304 mWindow->getToken());
5305 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5306 mWindow->setFocusable(true);
5307 mMirror->setFocusable(true);
5308 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5309 }
5310};
5311
5312TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5313 // Request focus on a mirrored window
5314 setFocusedWindow(mMirror);
5315
5316 // window gets focused
5317 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005318 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5319 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005320 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5321}
5322
5323// A focused & mirrored window remains focused only if the window and its mirror are both
5324// focusable.
5325TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5326 setFocusedWindow(mMirror);
5327
5328 // window gets focused
5329 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005330 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5331 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005332 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005333 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5334 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005335 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5336
5337 mMirror->setFocusable(false);
5338 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5339
5340 // window loses focus since one of the windows associated with the token in not focusable
5341 mWindow->consumeFocusEvent(false);
5342
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005343 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5344 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005345 mWindow->assertNoEvents();
5346}
5347
5348// A focused & mirrored window remains focused until the window and its mirror both become
5349// invisible.
5350TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5351 setFocusedWindow(mMirror);
5352
5353 // window gets focused
5354 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005355 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5356 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005357 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005358 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5359 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005360 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5361
5362 mMirror->setVisible(false);
5363 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5364
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005365 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5366 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005367 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005368 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5369 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005370 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5371
5372 mWindow->setVisible(false);
5373 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5374
5375 // window loses focus only after all windows associated with the token become invisible.
5376 mWindow->consumeFocusEvent(false);
5377
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005378 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5379 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005380 mWindow->assertNoEvents();
5381}
5382
5383// A focused & mirrored window remains focused until both windows are removed.
5384TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
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 // single window is removed but the window token remains focused
5397 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5398
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005399 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5400 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005401 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005402 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5403 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005404 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5405
5406 // Both windows are removed
5407 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5408 mWindow->consumeFocusEvent(false);
5409
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005410 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5411 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005412 mWindow->assertNoEvents();
5413}
5414
5415// Focus request can be pending until one window becomes visible.
5416TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5417 // Request focus on an invisible mirror.
5418 mWindow->setVisible(false);
5419 mMirror->setVisible(false);
5420 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5421 setFocusedWindow(mMirror);
5422
5423 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005424 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005425 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005426 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005427
5428 mMirror->setVisible(true);
5429 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5430
5431 // window gets focused
5432 mWindow->consumeFocusEvent(true);
5433 // window gets the pending key event
5434 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5435}
Prabir Pradhan99987712020-11-10 18:43:05 -08005436
5437class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5438protected:
5439 std::shared_ptr<FakeApplicationHandle> mApp;
5440 sp<FakeWindowHandle> mWindow;
5441 sp<FakeWindowHandle> mSecondWindow;
5442
5443 void SetUp() override {
5444 InputDispatcherTest::SetUp();
5445 mApp = std::make_shared<FakeApplicationHandle>();
5446 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5447 mWindow->setFocusable(true);
5448 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5449 mSecondWindow->setFocusable(true);
5450
5451 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5452 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5453
5454 setFocusedWindow(mWindow);
5455 mWindow->consumeFocusEvent(true);
5456 }
5457
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005458 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5459 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005460 mDispatcher->notifyPointerCaptureChanged(&args);
5461 }
5462
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005463 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5464 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005465 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005466 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5467 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005468 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005469 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005470 }
5471};
5472
5473TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5474 // Ensure that capture cannot be obtained for unfocused windows.
5475 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5476 mFakePolicy->assertSetPointerCaptureNotCalled();
5477 mSecondWindow->assertNoEvents();
5478
5479 // Ensure that capture can be enabled from the focus window.
5480 requestAndVerifyPointerCapture(mWindow, true);
5481
5482 // Ensure that capture cannot be disabled from a window that does not have capture.
5483 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5484 mFakePolicy->assertSetPointerCaptureNotCalled();
5485
5486 // Ensure that capture can be disabled from the window with capture.
5487 requestAndVerifyPointerCapture(mWindow, false);
5488}
5489
5490TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005491 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005492
5493 setFocusedWindow(mSecondWindow);
5494
5495 // Ensure that the capture disabled event was sent first.
5496 mWindow->consumeCaptureEvent(false);
5497 mWindow->consumeFocusEvent(false);
5498 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005499 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005500
5501 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005502 notifyPointerCaptureChanged({});
5503 notifyPointerCaptureChanged(request);
5504 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005505 mWindow->assertNoEvents();
5506 mSecondWindow->assertNoEvents();
5507 mFakePolicy->assertSetPointerCaptureNotCalled();
5508}
5509
5510TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005511 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005512
5513 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005514 notifyPointerCaptureChanged({});
5515 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005516
5517 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005518 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005519 mWindow->consumeCaptureEvent(false);
5520 mWindow->assertNoEvents();
5521}
5522
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005523TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5524 requestAndVerifyPointerCapture(mWindow, true);
5525
5526 // The first window loses focus.
5527 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005528 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005529 mWindow->consumeCaptureEvent(false);
5530
5531 // Request Pointer Capture from the second window before the notification from InputReader
5532 // arrives.
5533 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005534 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005535
5536 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005537 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005538
5539 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005540 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005541
5542 mSecondWindow->consumeFocusEvent(true);
5543 mSecondWindow->consumeCaptureEvent(true);
5544}
5545
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005546TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5547 // App repeatedly enables and disables capture.
5548 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5549 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5550 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5551 mFakePolicy->assertSetPointerCaptureCalled(false);
5552 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5553 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5554
5555 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5556 // first request is now stale, this should do nothing.
5557 notifyPointerCaptureChanged(firstRequest);
5558 mWindow->assertNoEvents();
5559
5560 // InputReader notifies that the second request was enabled.
5561 notifyPointerCaptureChanged(secondRequest);
5562 mWindow->consumeCaptureEvent(true);
5563}
5564
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005565class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5566protected:
5567 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005568
5569 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5570 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5571
5572 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5573 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5574
5575 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5576 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5577 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5578 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5579 MAXIMUM_OBSCURING_OPACITY);
5580
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005581 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005582 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005583 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005584
5585 sp<FakeWindowHandle> mTouchWindow;
5586
5587 virtual void SetUp() override {
5588 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005589 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005590 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5591 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5592 }
5593
5594 virtual void TearDown() override {
5595 InputDispatcherTest::TearDown();
5596 mTouchWindow.clear();
5597 }
5598
chaviw3277faf2021-05-19 16:45:23 -05005599 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5600 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005601 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005602 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005603 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005604 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005605 return window;
5606 }
5607
5608 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5609 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5610 sp<FakeWindowHandle> window =
5611 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5612 // Generate an arbitrary PID based on the UID
5613 window->setOwnerInfo(1777 + (uid % 10000), uid);
5614 return window;
5615 }
5616
5617 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5618 NotifyMotionArgs args =
5619 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5620 ADISPLAY_ID_DEFAULT, points);
5621 mDispatcher->notifyMotion(&args);
5622 }
5623};
5624
5625TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005626 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005627 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005628 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005629
5630 touch();
5631
5632 mTouchWindow->assertNoEvents();
5633}
5634
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005635TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005636 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5637 const sp<FakeWindowHandle>& w =
5638 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5639 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5640
5641 touch();
5642
5643 mTouchWindow->assertNoEvents();
5644}
5645
5646TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005647 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5648 const sp<FakeWindowHandle>& w =
5649 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5651
5652 touch();
5653
5654 w->assertNoEvents();
5655}
5656
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005657TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005658 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5659 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005660
5661 touch();
5662
5663 mTouchWindow->consumeAnyMotionDown();
5664}
5665
5666TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005667 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005668 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005669 w->setFrame(Rect(0, 0, 50, 50));
5670 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005671
5672 touch({PointF{100, 100}});
5673
5674 mTouchWindow->consumeAnyMotionDown();
5675}
5676
5677TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005678 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005679 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005680 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5681
5682 touch();
5683
5684 mTouchWindow->consumeAnyMotionDown();
5685}
5686
5687TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5688 const sp<FakeWindowHandle>& w =
5689 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5690 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005691
5692 touch();
5693
5694 mTouchWindow->consumeAnyMotionDown();
5695}
5696
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005697TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5698 const sp<FakeWindowHandle>& w =
5699 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5700 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5701
5702 touch();
5703
5704 w->assertNoEvents();
5705}
5706
5707/**
5708 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5709 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5710 * window, the occluding window will still receive ACTION_OUTSIDE event.
5711 */
5712TEST_F(InputDispatcherUntrustedTouchesTest,
5713 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5714 const sp<FakeWindowHandle>& w =
5715 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005716 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005717 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5718
5719 touch();
5720
5721 w->consumeMotionOutside();
5722}
5723
5724TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5725 const sp<FakeWindowHandle>& w =
5726 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005727 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005728 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5729
5730 touch();
5731
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005732 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005733}
5734
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005735TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005736 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005737 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5738 OPACITY_BELOW_THRESHOLD);
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, WindowWithOpacityAtThreshold_AllowsTouch) {
5747 const sp<FakeWindowHandle>& w =
5748 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5749 MAXIMUM_OBSCURING_OPACITY);
5750 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005751
5752 touch();
5753
5754 mTouchWindow->consumeAnyMotionDown();
5755}
5756
5757TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005758 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005759 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5760 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005761 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5762
5763 touch();
5764
5765 mTouchWindow->assertNoEvents();
5766}
5767
5768TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5769 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5770 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005771 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5772 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005773 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005774 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5775 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005776 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5777
5778 touch();
5779
5780 mTouchWindow->assertNoEvents();
5781}
5782
5783TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5784 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5785 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005786 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5787 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005788 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005789 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5790 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005791 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5792
5793 touch();
5794
5795 mTouchWindow->consumeAnyMotionDown();
5796}
5797
5798TEST_F(InputDispatcherUntrustedTouchesTest,
5799 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5800 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005801 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5802 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005803 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005804 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5805 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005806 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5807
5808 touch();
5809
5810 mTouchWindow->consumeAnyMotionDown();
5811}
5812
5813TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5814 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005815 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5816 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005817 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005818 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5819 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005820 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005821
5822 touch();
5823
5824 mTouchWindow->assertNoEvents();
5825}
5826
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005827TEST_F(InputDispatcherUntrustedTouchesTest,
5828 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5829 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005830 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5831 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005832 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005833 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5834 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005835 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5836
5837 touch();
5838
5839 mTouchWindow->assertNoEvents();
5840}
5841
5842TEST_F(InputDispatcherUntrustedTouchesTest,
5843 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5844 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005845 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5846 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005847 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005848 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5849 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005850 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5851
5852 touch();
5853
5854 mTouchWindow->consumeAnyMotionDown();
5855}
5856
5857TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5858 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005859 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5860 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005861 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5862
5863 touch();
5864
5865 mTouchWindow->consumeAnyMotionDown();
5866}
5867
5868TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5869 const sp<FakeWindowHandle>& w =
5870 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5871 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5872
5873 touch();
5874
5875 mTouchWindow->consumeAnyMotionDown();
5876}
5877
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005878TEST_F(InputDispatcherUntrustedTouchesTest,
5879 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5880 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5881 const sp<FakeWindowHandle>& w =
5882 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5883 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5884
5885 touch();
5886
5887 mTouchWindow->assertNoEvents();
5888}
5889
5890TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5891 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5892 const sp<FakeWindowHandle>& w =
5893 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5894 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5895
5896 touch();
5897
5898 mTouchWindow->consumeAnyMotionDown();
5899}
5900
5901TEST_F(InputDispatcherUntrustedTouchesTest,
5902 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5903 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5904 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005905 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5906 OPACITY_ABOVE_THRESHOLD);
5907 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5908
5909 touch();
5910
5911 mTouchWindow->consumeAnyMotionDown();
5912}
5913
5914TEST_F(InputDispatcherUntrustedTouchesTest,
5915 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5916 const sp<FakeWindowHandle>& w1 =
5917 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5918 OPACITY_BELOW_THRESHOLD);
5919 const sp<FakeWindowHandle>& w2 =
5920 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5921 OPACITY_BELOW_THRESHOLD);
5922 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5923
5924 touch();
5925
5926 mTouchWindow->assertNoEvents();
5927}
5928
5929/**
5930 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5931 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5932 * (which alone would result in allowing touches) does not affect the blocking behavior.
5933 */
5934TEST_F(InputDispatcherUntrustedTouchesTest,
5935 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5936 const sp<FakeWindowHandle>& wB =
5937 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5938 OPACITY_BELOW_THRESHOLD);
5939 const sp<FakeWindowHandle>& wC =
5940 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5941 OPACITY_BELOW_THRESHOLD);
5942 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5943
5944 touch();
5945
5946 mTouchWindow->assertNoEvents();
5947}
5948
5949/**
5950 * This test is testing that a window from a different UID but with same application token doesn't
5951 * block the touch. Apps can share the application token for close UI collaboration for example.
5952 */
5953TEST_F(InputDispatcherUntrustedTouchesTest,
5954 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5955 const sp<FakeWindowHandle>& w =
5956 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5957 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005958 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5959
5960 touch();
5961
5962 mTouchWindow->consumeAnyMotionDown();
5963}
5964
arthurhungb89ccb02020-12-30 16:19:01 +08005965class InputDispatcherDragTests : public InputDispatcherTest {
5966protected:
5967 std::shared_ptr<FakeApplicationHandle> mApp;
5968 sp<FakeWindowHandle> mWindow;
5969 sp<FakeWindowHandle> mSecondWindow;
5970 sp<FakeWindowHandle> mDragWindow;
5971
5972 void SetUp() override {
5973 InputDispatcherTest::SetUp();
5974 mApp = std::make_shared<FakeApplicationHandle>();
5975 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5976 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005977
5978 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5979 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005980
5981 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5982 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5983 }
5984
5985 // Start performing drag, we will create a drag window and transfer touch to it.
5986 void performDrag() {
5987 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5988 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5989 {50, 50}))
5990 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5991
5992 // Window should receive motion event.
5993 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5994
5995 // The drag window covers the entire display
5996 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5997 mDispatcher->setInputWindows(
5998 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5999
6000 // Transfer touch focus to the drag window
6001 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6002 true /* isDragDrop */);
6003 mWindow->consumeMotionCancel();
6004 mDragWindow->consumeMotionDown();
6005 }
arthurhung6d4bed92021-03-17 11:59:33 +08006006
6007 // Start performing drag, we will create a drag window and transfer touch to it.
6008 void performStylusDrag() {
6009 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6010 injectMotionEvent(mDispatcher,
6011 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6012 AINPUT_SOURCE_STYLUS)
6013 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6014 .pointer(PointerBuilder(0,
6015 AMOTION_EVENT_TOOL_TYPE_STYLUS)
6016 .x(50)
6017 .y(50))
6018 .build()));
6019 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6020
6021 // The drag window covers the entire display
6022 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
6023 mDispatcher->setInputWindows(
6024 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6025
6026 // Transfer touch focus to the drag window
6027 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6028 true /* isDragDrop */);
6029 mWindow->consumeMotionCancel();
6030 mDragWindow->consumeMotionDown();
6031 }
arthurhungb89ccb02020-12-30 16:19:01 +08006032};
6033
6034TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
6035 performDrag();
6036
6037 // Move on window.
6038 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6039 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6040 ADISPLAY_ID_DEFAULT, {50, 50}))
6041 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6042 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6043 mWindow->consumeDragEvent(false, 50, 50);
6044 mSecondWindow->assertNoEvents();
6045
6046 // Move to another window.
6047 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6048 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6049 ADISPLAY_ID_DEFAULT, {150, 50}))
6050 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6051 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6052 mWindow->consumeDragEvent(true, 150, 50);
6053 mSecondWindow->consumeDragEvent(false, 50, 50);
6054
6055 // Move back to original window.
6056 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6057 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6058 ADISPLAY_ID_DEFAULT, {50, 50}))
6059 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6060 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6061 mWindow->consumeDragEvent(false, 50, 50);
6062 mSecondWindow->consumeDragEvent(true, -50, 50);
6063
6064 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6065 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6066 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6067 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6068 mWindow->assertNoEvents();
6069 mSecondWindow->assertNoEvents();
6070}
6071
arthurhungf452d0b2021-01-06 00:19:52 +08006072TEST_F(InputDispatcherDragTests, DragAndDrop) {
6073 performDrag();
6074
6075 // Move on window.
6076 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6077 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6078 ADISPLAY_ID_DEFAULT, {50, 50}))
6079 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6080 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6081 mWindow->consumeDragEvent(false, 50, 50);
6082 mSecondWindow->assertNoEvents();
6083
6084 // Move to another window.
6085 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6086 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6087 ADISPLAY_ID_DEFAULT, {150, 50}))
6088 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6089 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6090 mWindow->consumeDragEvent(true, 150, 50);
6091 mSecondWindow->consumeDragEvent(false, 50, 50);
6092
6093 // drop to another window.
6094 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6095 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6096 {150, 50}))
6097 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6098 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6099 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6100 mWindow->assertNoEvents();
6101 mSecondWindow->assertNoEvents();
6102}
6103
arthurhung6d4bed92021-03-17 11:59:33 +08006104TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6105 performStylusDrag();
6106
6107 // Move on window and keep button pressed.
6108 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6109 injectMotionEvent(mDispatcher,
6110 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6111 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6112 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6113 .x(50)
6114 .y(50))
6115 .build()))
6116 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6117 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6118 mWindow->consumeDragEvent(false, 50, 50);
6119 mSecondWindow->assertNoEvents();
6120
6121 // Move to another window and release button, expect to drop item.
6122 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6123 injectMotionEvent(mDispatcher,
6124 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6125 .buttonState(0)
6126 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6127 .x(150)
6128 .y(50))
6129 .build()))
6130 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6131 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6132 mWindow->assertNoEvents();
6133 mSecondWindow->assertNoEvents();
6134 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6135
6136 // nothing to the window.
6137 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6138 injectMotionEvent(mDispatcher,
6139 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6140 .buttonState(0)
6141 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6142 .x(150)
6143 .y(50))
6144 .build()))
6145 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6146 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6147 mWindow->assertNoEvents();
6148 mSecondWindow->assertNoEvents();
6149}
6150
Arthur Hung6d0571e2021-04-09 20:18:16 +08006151TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6152 performDrag();
6153
6154 // Set second window invisible.
6155 mSecondWindow->setVisible(false);
6156 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6157
6158 // Move on window.
6159 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6160 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6161 ADISPLAY_ID_DEFAULT, {50, 50}))
6162 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6163 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6164 mWindow->consumeDragEvent(false, 50, 50);
6165 mSecondWindow->assertNoEvents();
6166
6167 // Move to another window.
6168 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6169 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6170 ADISPLAY_ID_DEFAULT, {150, 50}))
6171 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6172 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6173 mWindow->consumeDragEvent(true, 150, 50);
6174 mSecondWindow->assertNoEvents();
6175
6176 // drop to another window.
6177 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6178 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6179 {150, 50}))
6180 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6181 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6182 mFakePolicy->assertDropTargetEquals(nullptr);
6183 mWindow->assertNoEvents();
6184 mSecondWindow->assertNoEvents();
6185}
6186
Vishnu Nair062a8672021-09-03 16:07:44 -07006187class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6188
6189TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6190 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6191 sp<FakeWindowHandle> window =
6192 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006193 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006194 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6195 window->setFocusable(true);
6196 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6197 setFocusedWindow(window);
6198 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6199
6200 // With the flag set, window should not get any input
6201 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6202 mDispatcher->notifyKey(&keyArgs);
6203 window->assertNoEvents();
6204
6205 NotifyMotionArgs motionArgs =
6206 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6207 ADISPLAY_ID_DEFAULT);
6208 mDispatcher->notifyMotion(&motionArgs);
6209 window->assertNoEvents();
6210
6211 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006212 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006213 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6214
6215 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6216 mDispatcher->notifyKey(&keyArgs);
6217 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6218
6219 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6220 ADISPLAY_ID_DEFAULT);
6221 mDispatcher->notifyMotion(&motionArgs);
6222 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6223 window->assertNoEvents();
6224}
6225
6226TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6227 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6228 std::make_shared<FakeApplicationHandle>();
6229 sp<FakeWindowHandle> obscuringWindow =
6230 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6231 ADISPLAY_ID_DEFAULT);
6232 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6233 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006234 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006235 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6236 sp<FakeWindowHandle> window =
6237 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006238 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006239 window->setOwnerInfo(222, 222);
6240 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6241 window->setFocusable(true);
6242 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6243 setFocusedWindow(window);
6244 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6245
6246 // With the flag set, window should not get any input
6247 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6248 mDispatcher->notifyKey(&keyArgs);
6249 window->assertNoEvents();
6250
6251 NotifyMotionArgs motionArgs =
6252 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6253 ADISPLAY_ID_DEFAULT);
6254 mDispatcher->notifyMotion(&motionArgs);
6255 window->assertNoEvents();
6256
6257 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006258 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006259 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6260
6261 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6262 mDispatcher->notifyKey(&keyArgs);
6263 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6264
6265 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6266 ADISPLAY_ID_DEFAULT);
6267 mDispatcher->notifyMotion(&motionArgs);
6268 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6269 window->assertNoEvents();
6270}
6271
6272TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6273 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6274 std::make_shared<FakeApplicationHandle>();
6275 sp<FakeWindowHandle> obscuringWindow =
6276 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6277 ADISPLAY_ID_DEFAULT);
6278 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6279 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006280 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006281 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6282 sp<FakeWindowHandle> window =
6283 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006284 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006285 window->setOwnerInfo(222, 222);
6286 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6287 window->setFocusable(true);
6288 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6289 setFocusedWindow(window);
6290 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6291
6292 // With the flag set, window should not get any input
6293 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6294 mDispatcher->notifyKey(&keyArgs);
6295 window->assertNoEvents();
6296
6297 NotifyMotionArgs motionArgs =
6298 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6299 ADISPLAY_ID_DEFAULT);
6300 mDispatcher->notifyMotion(&motionArgs);
6301 window->assertNoEvents();
6302
6303 // When the window is no longer obscured because it went on top, it should get input
6304 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6305
6306 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6307 mDispatcher->notifyKey(&keyArgs);
6308 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6309
6310 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6311 ADISPLAY_ID_DEFAULT);
6312 mDispatcher->notifyMotion(&motionArgs);
6313 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6314 window->assertNoEvents();
6315}
6316
Antonio Kantekf16f2832021-09-28 04:39:20 +00006317class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6318protected:
6319 std::shared_ptr<FakeApplicationHandle> mApp;
6320 sp<FakeWindowHandle> mWindow;
6321 sp<FakeWindowHandle> mSecondWindow;
6322
6323 void SetUp() override {
6324 InputDispatcherTest::SetUp();
6325
6326 mApp = std::make_shared<FakeApplicationHandle>();
6327 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6328 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006329 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006330 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6331 mSecondWindow->setFocusable(true);
6332
6333 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6334 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006335 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006336
6337 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
6338 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, INJECTOR_PID,
6339 INJECTOR_UID, /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006340 }
6341
Antonio Kantekea47acb2021-12-23 12:41:25 -08006342 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006343 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006344 mWindow->consumeTouchModeEvent(inTouchMode);
6345 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6346 }
6347};
6348
Antonio Kantek26defcf2022-02-08 01:12:27 +00006349TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006350 const WindowInfo& windowInfo = *mWindow->getInfo();
6351 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6352 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006353}
6354
Antonio Kantek26defcf2022-02-08 01:12:27 +00006355TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6356 const WindowInfo& windowInfo = *mWindow->getInfo();
6357 int32_t ownerPid = windowInfo.ownerPid;
6358 int32_t ownerUid = windowInfo.ownerUid;
6359 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6360 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6361 ownerUid, /* hasPermission */ false));
6362 mWindow->assertNoEvents();
6363 mSecondWindow->assertNoEvents();
6364}
6365
6366TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6367 const WindowInfo& windowInfo = *mWindow->getInfo();
6368 int32_t ownerPid = windowInfo.ownerPid;
6369 int32_t ownerUid = windowInfo.ownerUid;
6370 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6371 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6372 /* hasPermission */ true);
6373}
6374
Antonio Kantekf16f2832021-09-28 04:39:20 +00006375TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006376 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006377 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6378 windowInfo.ownerPid, windowInfo.ownerUid,
6379 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006380 mWindow->assertNoEvents();
6381 mSecondWindow->assertNoEvents();
6382}
6383
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006384class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6385public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006386 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006387 std::shared_ptr<FakeApplicationHandle> application =
6388 std::make_shared<FakeApplicationHandle>();
6389 std::string name = "Fake Spy ";
6390 name += std::to_string(mSpyCount++);
6391 sp<FakeWindowHandle> spy =
6392 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006393 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006394 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006395 return spy;
6396 }
6397
6398 sp<FakeWindowHandle> createForeground() {
6399 std::shared_ptr<FakeApplicationHandle> application =
6400 std::make_shared<FakeApplicationHandle>();
6401 sp<FakeWindowHandle> window =
6402 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006403 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006404 return window;
6405 }
6406
6407private:
6408 int mSpyCount{0};
6409};
6410
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006411using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006412/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006413 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6414 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006415TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6416 ScopedSilentDeath _silentDeath;
6417
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006418 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006419 spy->setTrustedOverlay(false);
6420 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6421 ".* not a trusted overlay");
6422}
6423
6424/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006425 * Input injection into a display with a spy window but no foreground windows should succeed.
6426 */
6427TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006428 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006429 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6430
6431 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6432 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6433 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6434 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6435}
6436
6437/**
6438 * Verify the order in which different input windows receive events. The touched foreground window
6439 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6440 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6441 * receive events before ones belows it.
6442 *
6443 * Here, we set up a scenario with four windows in the following Z order from the top:
6444 * spy1, spy2, window, spy3.
6445 * We then inject an event and verify that the foreground "window" receives it first, followed by
6446 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6447 * window.
6448 */
6449TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6450 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006451 auto spy1 = createSpy();
6452 auto spy2 = createSpy();
6453 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006454 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6455 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6456 const size_t numChannels = channels.size();
6457
Michael Wright8e9a8562022-02-09 13:44:29 +00006458 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006459 if (!epollFd.ok()) {
6460 FAIL() << "Failed to create epoll fd";
6461 }
6462
6463 for (size_t i = 0; i < numChannels; i++) {
6464 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6465 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6466 FAIL() << "Failed to add fd to epoll";
6467 }
6468 }
6469
6470 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6471 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6472 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6473
6474 std::vector<size_t> eventOrder;
6475 std::vector<struct epoll_event> events(numChannels);
6476 for (;;) {
6477 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6478 (100ms).count());
6479 if (nFds < 0) {
6480 FAIL() << "Failed to call epoll_wait";
6481 }
6482 if (nFds == 0) {
6483 break; // epoll_wait timed out
6484 }
6485 for (int i = 0; i < nFds; i++) {
6486 ASSERT_EQ(EPOLLIN, events[i].events);
6487 eventOrder.push_back(events[i].data.u64);
6488 channels[i]->consumeMotionDown();
6489 }
6490 }
6491
6492 // Verify the order in which the events were received.
6493 EXPECT_EQ(3u, eventOrder.size());
6494 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6495 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6496 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6497}
6498
6499/**
6500 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6501 */
6502TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6503 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006504 auto spy = createSpy();
6505 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006506 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6507
6508 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6509 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6510 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6511 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6512 spy->assertNoEvents();
6513}
6514
6515/**
6516 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6517 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6518 * to the window.
6519 */
6520TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6521 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006522 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006523 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6524 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6525
6526 // Inject an event outside the spy window's touchable region.
6527 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6528 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6529 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6530 window->consumeMotionDown();
6531 spy->assertNoEvents();
6532 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6533 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6534 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6535 window->consumeMotionUp();
6536 spy->assertNoEvents();
6537
6538 // Inject an event inside the spy window's touchable region.
6539 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6540 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6541 {5, 10}))
6542 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6543 window->consumeMotionDown();
6544 spy->consumeMotionDown();
6545}
6546
6547/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006548 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006549 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006550 */
6551TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6552 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006553 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006554 auto spy = createSpy();
6555 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006556 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006557 spy->setFrame(Rect{0, 0, 20, 20});
6558 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6559
6560 // Inject an event outside the spy window's frame and touchable region.
6561 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006562 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6563 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006564 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6565 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006566 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006567}
6568
6569/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006570 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6571 * any other windows - including other spy windows - will also be cancelled.
6572 */
6573TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6574 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006575 auto spy1 = createSpy();
6576 auto spy2 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006577 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6578
6579 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6580 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6581 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6582 window->consumeMotionDown();
6583 spy1->consumeMotionDown();
6584 spy2->consumeMotionDown();
6585
6586 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006587 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006588 spy2->assertNoEvents();
6589 spy1->consumeMotionCancel();
6590 window->consumeMotionCancel();
6591
6592 // The rest of the gesture should only be sent to the second spy window.
6593 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6594 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6595 ADISPLAY_ID_DEFAULT))
6596 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6597 spy2->consumeMotionMove();
6598 spy1->assertNoEvents();
6599 window->assertNoEvents();
6600}
6601
6602/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006603 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
6604 * in the middle of the gesture.
6605 */
6606TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
6607 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006608 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006609 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6610
6611 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6612 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6613 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6614 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6615 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6616
6617 window->releaseChannel();
6618
6619 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6620
6621 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6622 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6623 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6624 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6625}
6626
6627/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006628 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
6629 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006630 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006631TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006632 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006633 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006634
6635 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6636
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006637 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006638 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6639 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6640 {100, 200}))
6641 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006642 spy->consumeMotionDown();
6643 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006644
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006645 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006646 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006647 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006648
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006649 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006650 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006651 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006652 .displayId(ADISPLAY_ID_DEFAULT)
6653 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6654 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6655 .x(100)
6656 .y(200))
6657 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6658 .build();
6659 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6660 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6661 InputEventInjectionSync::WAIT_FOR_RESULT))
6662 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6663
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006664 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6665
6666 // Third finger goes down outside all windows, so injection should fail.
6667 const MotionEvent thirdFingerDownEvent =
6668 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6669 (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6670 AINPUT_SOURCE_TOUCHSCREEN)
6671 .displayId(ADISPLAY_ID_DEFAULT)
6672 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6673 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6674 .x(100)
6675 .y(200))
6676 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6677 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
6678 .build();
6679 ASSERT_EQ(InputEventInjectionResult::FAILED,
6680 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
6681 InputEventInjectionSync::WAIT_FOR_RESULT))
6682 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6683
6684 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006685 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006686}
6687
6688/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006689 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6690 * pointers that are down within its bounds.
6691 */
6692TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6693 auto windowLeft = createForeground();
6694 windowLeft->setFrame({0, 0, 100, 200});
6695 auto windowRight = createForeground();
6696 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006697 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006698 spy->setFrame({0, 0, 200, 200});
6699 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6700
6701 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6702 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6703 {50, 50}))
6704 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6705 windowLeft->consumeMotionDown();
6706 spy->consumeMotionDown();
6707
6708 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006709 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006710 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6711 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6712 .pointer(
6713 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6714 .build();
6715 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6716 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6717 InputEventInjectionSync::WAIT_FOR_RESULT))
6718 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6719 windowRight->consumeMotionDown();
6720 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6721}
6722
6723/**
6724 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6725 * the spy should receive the second pointer with ACTION_DOWN.
6726 */
6727TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6728 auto window = createForeground();
6729 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006730 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006731 spyRight->setFrame({100, 0, 200, 200});
6732 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6733
6734 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6735 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6736 {50, 50}))
6737 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6738 window->consumeMotionDown();
6739 spyRight->assertNoEvents();
6740
6741 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006742 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006743 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6744 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6745 .pointer(
6746 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6747 .build();
6748 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6749 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6750 InputEventInjectionSync::WAIT_FOR_RESULT))
6751 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6752 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6753 spyRight->consumeMotionDown();
6754}
6755
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006756/**
6757 * The spy window should not be able to affect whether or not touches are split. Only the foreground
6758 * windows should be allowed to control split touch.
6759 */
6760TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006761 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006762 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006763 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006764 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006765
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006766 auto window = createForeground();
6767 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006768
6769 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6770
6771 // First finger down, no window touched.
6772 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6773 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6774 {100, 200}))
6775 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6776 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6777 window->assertNoEvents();
6778
6779 // Second finger down on window, the window should receive touch down.
6780 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006781 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006782 .displayId(ADISPLAY_ID_DEFAULT)
6783 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6784 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6785 .x(100)
6786 .y(200))
6787 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6788 .build();
6789 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6790 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6791 InputEventInjectionSync::WAIT_FOR_RESULT))
6792 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6793
6794 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6795 spy->consumeMotionPointerDown(1 /* pointerIndex */);
6796}
6797
6798/**
6799 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
6800 * do not receive key events.
6801 */
6802TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006803 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006804 spy->setFocusable(false);
6805
6806 auto window = createForeground();
6807 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6808 setFocusedWindow(window);
6809 window->consumeFocusEvent(true);
6810
6811 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6812 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6813 window->consumeKeyDown(ADISPLAY_ID_NONE);
6814
6815 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6816 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6817 window->consumeKeyUp(ADISPLAY_ID_NONE);
6818
6819 spy->assertNoEvents();
6820}
6821
Prabir Pradhand65552b2021-10-07 11:23:50 -07006822class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6823public:
6824 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6825 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6826 std::make_shared<FakeApplicationHandle>();
6827 sp<FakeWindowHandle> overlay =
6828 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6829 ADISPLAY_ID_DEFAULT);
6830 overlay->setFocusable(false);
6831 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006832 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006833 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006834 overlay->setTrustedOverlay(true);
6835
6836 std::shared_ptr<FakeApplicationHandle> application =
6837 std::make_shared<FakeApplicationHandle>();
6838 sp<FakeWindowHandle> window =
6839 new FakeWindowHandle(application, mDispatcher, "Application window",
6840 ADISPLAY_ID_DEFAULT);
6841 window->setFocusable(true);
6842 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006843
6844 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6845 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6846 setFocusedWindow(window);
6847 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6848 return {std::move(overlay), std::move(window)};
6849 }
6850
6851 void sendFingerEvent(int32_t action) {
6852 NotifyMotionArgs motionArgs =
6853 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6854 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6855 mDispatcher->notifyMotion(&motionArgs);
6856 }
6857
6858 void sendStylusEvent(int32_t action) {
6859 NotifyMotionArgs motionArgs =
6860 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6861 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6862 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6863 mDispatcher->notifyMotion(&motionArgs);
6864 }
6865};
6866
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006867using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
6868
6869TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
6870 ScopedSilentDeath _silentDeath;
6871
Prabir Pradhand65552b2021-10-07 11:23:50 -07006872 auto [overlay, window] = setupStylusOverlayScenario();
6873 overlay->setTrustedOverlay(false);
6874 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6875 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6876 ".* not a trusted overlay");
6877}
6878
6879TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6880 auto [overlay, window] = setupStylusOverlayScenario();
6881 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6882
6883 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6884 overlay->consumeMotionDown();
6885 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6886 overlay->consumeMotionUp();
6887
6888 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6889 window->consumeMotionDown();
6890 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6891 window->consumeMotionUp();
6892
6893 overlay->assertNoEvents();
6894 window->assertNoEvents();
6895}
6896
6897TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6898 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006899 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006900 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6901
6902 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6903 overlay->consumeMotionDown();
6904 window->consumeMotionDown();
6905 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6906 overlay->consumeMotionUp();
6907 window->consumeMotionUp();
6908
6909 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6910 window->consumeMotionDown();
6911 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6912 window->consumeMotionUp();
6913
6914 overlay->assertNoEvents();
6915 window->assertNoEvents();
6916}
6917
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00006918/**
6919 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
6920 * The scenario is as follows:
6921 * - The stylus interceptor overlay is configured as a spy window.
6922 * - The stylus interceptor spy receives the start of a new stylus gesture.
6923 * - It pilfers pointers and then configures itself to no longer be a spy.
6924 * - The stylus interceptor continues to receive the rest of the gesture.
6925 */
6926TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
6927 auto [overlay, window] = setupStylusOverlayScenario();
6928 overlay->setSpy(true);
6929 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6930
6931 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6932 overlay->consumeMotionDown();
6933 window->consumeMotionDown();
6934
6935 // The interceptor pilfers the pointers.
6936 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
6937 window->consumeMotionCancel();
6938
6939 // The interceptor configures itself so that it is no longer a spy.
6940 overlay->setSpy(false);
6941 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6942
6943 // It continues to receive the rest of the stylus gesture.
6944 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
6945 overlay->consumeMotionMove();
6946 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6947 overlay->consumeMotionUp();
6948
6949 window->assertNoEvents();
6950}
6951
Garfield Tane84e6f92019-08-29 17:28:41 -07006952} // namespace android::inputdispatcher