blob: a324aa06f2bdd21a74b1191f16328b4fe6ffb832 [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);
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +000058static constexpr int32_t POINTER_2_DOWN =
59 AMOTION_EVENT_ACTION_POINTER_DOWN | (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080060static constexpr int32_t POINTER_1_UP =
61 AMOTION_EVENT_ACTION_POINTER_UP | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
62
Michael Wrightd02c5b62014-02-10 15:10:22 -080063// An arbitrary injector pid / uid pair that has permission to inject events.
64static const int32_t INJECTOR_PID = 999;
65static const int32_t INJECTOR_UID = 1001;
66
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000067// An arbitrary pid of the gesture monitor window
68static constexpr int32_t MONITOR_PID = 2001;
69
chaviwd1c23182019-12-20 18:44:56 -080070struct PointF {
71 float x;
72 float y;
73};
Michael Wrightd02c5b62014-02-10 15:10:22 -080074
Gang Wang342c9272020-01-13 13:15:04 -050075/**
76 * Return a DOWN key event with KEYCODE_A.
77 */
78static KeyEvent getTestKeyEvent() {
79 KeyEvent event;
80
Garfield Tanfbe732e2020-01-24 11:26:14 -080081 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
82 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
83 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050084 return event;
85}
86
Siarhei Vishniakouca205502021-07-16 21:31:58 +000087static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
88 ASSERT_EQ(expectedAction, receivedAction)
89 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
90 << MotionEvent::actionToString(receivedAction);
91}
92
Michael Wrightd02c5b62014-02-10 15:10:22 -080093// --- FakeInputDispatcherPolicy ---
94
95class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
96 InputDispatcherConfiguration mConfig;
97
Prabir Pradhanedd96402022-02-15 01:46:16 -080098 using AnrResult = std::pair<sp<IBinder>, int32_t /*pid*/>;
99
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000101 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800102
103public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000104 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +0800105
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800106 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700107 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
108 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
109 EXPECT_EQ(event.getDisplayId(), args.displayId);
110
111 const auto& keyEvent = static_cast<const KeyEvent&>(event);
112 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
113 EXPECT_EQ(keyEvent.getAction(), args.action);
114 });
Jackal Guof9696682018-10-05 12:23:23 +0800115 }
116
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700117 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
118 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
119 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
120 EXPECT_EQ(event.getDisplayId(), args.displayId);
121
122 const auto& motionEvent = static_cast<const MotionEvent&>(event);
123 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
124 EXPECT_EQ(motionEvent.getAction(), args.action);
125 EXPECT_EQ(motionEvent.getX(0), point.x);
126 EXPECT_EQ(motionEvent.getY(0), point.y);
127 EXPECT_EQ(motionEvent.getRawX(0), point.x);
128 EXPECT_EQ(motionEvent.getRawY(0), point.y);
129 });
Jackal Guof9696682018-10-05 12:23:23 +0800130 }
131
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700132 void assertFilterInputEventWasNotCalled() {
133 std::scoped_lock lock(mLock);
134 ASSERT_EQ(nullptr, mFilteredEvent);
135 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800136
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800137 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700138 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800139 ASSERT_TRUE(mConfigurationChangedTime)
140 << "Timed out waiting for configuration changed call";
141 ASSERT_EQ(*mConfigurationChangedTime, when);
142 mConfigurationChangedTime = std::nullopt;
143 }
144
145 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700146 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800147 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800148 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800149 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
150 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
151 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
152 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
153 mLastNotifySwitch = std::nullopt;
154 }
155
chaviwfd6d3512019-03-25 13:23:49 -0700156 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700157 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800158 ASSERT_EQ(touchedToken, mOnPointerDownToken);
159 mOnPointerDownToken.clear();
160 }
161
162 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700163 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800164 ASSERT_TRUE(mOnPointerDownToken == nullptr)
165 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700166 }
167
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700168 // This function must be called soon after the expected ANR timer starts,
169 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500170 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700171 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500172 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800173 std::unique_lock lock(mLock);
174 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500175 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800176 ASSERT_NO_FATAL_FAILURE(
177 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500178 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700179 }
180
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000181 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800182 const sp<WindowInfoHandle>& window) {
183 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
184 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
185 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500186 }
187
Prabir Pradhanedd96402022-02-15 01:46:16 -0800188 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
189 const sp<IBinder>& expectedToken,
190 int32_t expectedPid) {
191 std::unique_lock lock(mLock);
192 android::base::ScopedLockAssertion assumeLocked(mLock);
193 AnrResult result;
194 ASSERT_NO_FATAL_FAILURE(result =
195 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
196 const auto& [token, pid] = result;
197 ASSERT_EQ(expectedToken, token);
198 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500199 }
200
Prabir Pradhanedd96402022-02-15 01:46:16 -0800201 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000202 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500203 std::unique_lock lock(mLock);
204 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800205 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
206 const auto& [token, _] = result;
207 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000208 }
209
Prabir Pradhanedd96402022-02-15 01:46:16 -0800210 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
211 int32_t expectedPid) {
212 std::unique_lock lock(mLock);
213 android::base::ScopedLockAssertion assumeLocked(mLock);
214 AnrResult result;
215 ASSERT_NO_FATAL_FAILURE(
216 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
217 const auto& [token, pid] = result;
218 ASSERT_EQ(expectedToken, token);
219 ASSERT_EQ(expectedPid, pid);
220 }
221
222 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000223 sp<IBinder> getResponsiveWindowToken() {
224 std::unique_lock lock(mLock);
225 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800226 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
227 const auto& [token, _] = result;
228 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700229 }
230
231 void assertNotifyAnrWasNotCalled() {
232 std::scoped_lock lock(mLock);
233 ASSERT_TRUE(mAnrApplications.empty());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800234 ASSERT_TRUE(mAnrWindows.empty());
235 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500236 << "ANR was not called, but please also consume the 'connection is responsive' "
237 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700238 }
239
Garfield Tan1c7bc862020-01-28 13:24:04 -0800240 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
241 mConfig.keyRepeatTimeout = timeout;
242 mConfig.keyRepeatDelay = delay;
243 }
244
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000245 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800246 std::unique_lock lock(mLock);
247 base::ScopedLockAssertion assumeLocked(mLock);
248
249 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
250 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000251 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800252 enabled;
253 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000254 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
255 << ") to be called.";
256 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800257 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000258 auto request = *mPointerCaptureRequest;
259 mPointerCaptureRequest.reset();
260 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800261 }
262
263 void assertSetPointerCaptureNotCalled() {
264 std::unique_lock lock(mLock);
265 base::ScopedLockAssertion assumeLocked(mLock);
266
267 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000268 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800269 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000270 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800271 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000272 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800273 }
274
arthurhungf452d0b2021-01-06 00:19:52 +0800275 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
276 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800277 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800278 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800279 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800280 }
281
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800282 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
283 std::unique_lock lock(mLock);
284 base::ScopedLockAssertion assumeLocked(mLock);
285 std::optional<sp<IBinder>> receivedToken =
286 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
287 mNotifyInputChannelBroken);
288 ASSERT_TRUE(receivedToken.has_value());
289 ASSERT_EQ(token, *receivedToken);
290 }
291
Michael Wrightd02c5b62014-02-10 15:10:22 -0800292private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700293 std::mutex mLock;
294 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
295 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
296 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
297 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800298
Prabir Pradhan99987712020-11-10 18:43:05 -0800299 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000300
301 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800302
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700303 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700304 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800305 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
306 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700307 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800308 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
309 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700310
arthurhungf452d0b2021-01-06 00:19:52 +0800311 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800312 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800313
Prabir Pradhanedd96402022-02-15 01:46:16 -0800314 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
315 // for a specific container to become non-empty. When the container is non-empty, return the
316 // first entry from the container and erase it.
317 template <class T>
318 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
319 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
320 // If there is an ANR, Dispatcher won't be idle because there are still events
321 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
322 // before checking if ANR was called.
323 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
324 // to provide it some time to act. 100ms seems reasonable.
325 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
326 const std::chrono::time_point start = std::chrono::steady_clock::now();
327 std::optional<T> token =
328 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
329 if (!token.has_value()) {
330 ADD_FAILURE() << "Did not receive the ANR callback";
331 return {};
332 }
333
334 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
335 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
336 // the dispatcher started counting before this function was called
337 if (std::chrono::abs(timeout - waited) > 100ms) {
338 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
339 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
340 << "ms, but waited "
341 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
342 << "ms instead";
343 }
344 return *token;
345 }
346
347 template <class T>
348 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
349 std::queue<T>& storage,
350 std::unique_lock<std::mutex>& lock,
351 std::condition_variable& condition)
352 REQUIRES(mLock) {
353 condition.wait_for(lock, timeout,
354 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
355 if (storage.empty()) {
356 ADD_FAILURE() << "Did not receive the expected callback";
357 return std::nullopt;
358 }
359 T item = storage.front();
360 storage.pop();
361 return std::make_optional(item);
362 }
363
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600364 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700365 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800366 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800367 }
368
Prabir Pradhanedd96402022-02-15 01:46:16 -0800369 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
370 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700371 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800372 ASSERT_TRUE(pid.has_value());
373 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700374 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500375 }
376
Prabir Pradhanedd96402022-02-15 01:46:16 -0800377 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
378 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500379 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800380 ASSERT_TRUE(pid.has_value());
381 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500382 mNotifyAnr.notify_all();
383 }
384
385 void notifyNoFocusedWindowAnr(
386 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
387 std::scoped_lock lock(mLock);
388 mAnrApplications.push(applicationHandle);
389 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800390 }
391
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800392 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
393 std::scoped_lock lock(mLock);
394 mBrokenInputChannels.push(connectionToken);
395 mNotifyInputChannelBroken.notify_all();
396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800397
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600398 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700399
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600400 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700401 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
402 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
403 const std::vector<float>& values) override {}
404
405 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
406 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000407
Chris Yefb552902021-02-03 17:18:37 -0800408 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
409
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600410 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411 *outConfig = mConfig;
412 }
413
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600414 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700415 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800416 switch (inputEvent->getType()) {
417 case AINPUT_EVENT_TYPE_KEY: {
418 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800419 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800420 break;
421 }
422
423 case AINPUT_EVENT_TYPE_MOTION: {
424 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800425 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800426 break;
427 }
428 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800429 return true;
430 }
431
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600432 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800433
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600434 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800435
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600436 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437 return 0;
438 }
439
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600440 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800441 return false;
442 }
443
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600444 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
445 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700446 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800447 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
448 * essentially a passthrough for notifySwitch.
449 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800450 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800451 }
452
Sean Stoutb4e0a592021-02-23 07:34:53 -0800453 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800454
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800455 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
456 return pid == INJECTOR_PID && uid == INJECTOR_UID;
457 }
Jackal Guof9696682018-10-05 12:23:23 +0800458
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600459 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700460 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700461 mOnPointerDownToken = newToken;
462 }
463
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000464 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800465 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000466 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800467 mPointerCaptureChangedCondition.notify_all();
468 }
469
arthurhungf452d0b2021-01-06 00:19:52 +0800470 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
471 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800472 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800473 mDropTargetWindowToken = token;
474 }
475
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700476 void assertFilterInputEventWasCalledInternal(
477 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700478 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800479 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700480 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800481 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800482 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800483};
484
Michael Wrightd02c5b62014-02-10 15:10:22 -0800485// --- InputDispatcherTest ---
486
487class InputDispatcherTest : public testing::Test {
488protected:
489 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700490 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800491
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000492 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700494 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800495 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000496 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700497 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800498 }
499
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000500 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700501 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800502 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700503 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800504 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700505
506 /**
507 * Used for debugging when writing the test
508 */
509 void dumpDispatcherState() {
510 std::string dump;
511 mDispatcher->dump(dump);
512 std::stringstream ss(dump);
513 std::string to;
514
515 while (std::getline(ss, to, '\n')) {
516 ALOGE("%s", to.c_str());
517 }
518 }
Vishnu Nair958da932020-08-21 17:12:37 -0700519
chaviw3277faf2021-05-19 16:45:23 -0500520 void setFocusedWindow(const sp<WindowInfoHandle>& window,
521 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700522 FocusRequest request;
523 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000524 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700525 if (focusedWindow) {
526 request.focusedToken = focusedWindow->getToken();
527 }
528 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
529 request.displayId = window->getInfo()->displayId;
530 mDispatcher->setFocusedWindow(request);
531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800532};
533
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
535 KeyEvent event;
536
537 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800538 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
539 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600540 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
541 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800542 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700543 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800544 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800545 << "Should reject key events with undefined action.";
546
547 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800548 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
549 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600550 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800551 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700552 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800553 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554 << "Should reject key events with ACTION_MULTIPLE.";
555}
556
557TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
558 MotionEvent event;
559 PointerProperties pointerProperties[MAX_POINTERS + 1];
560 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800561 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 pointerProperties[i].clear();
563 pointerProperties[i].id = i;
564 pointerCoords[i].clear();
565 }
566
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800567 // Some constants commonly used below
568 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
569 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
570 constexpr int32_t metaState = AMETA_NONE;
571 constexpr MotionClassification classification = MotionClassification::NONE;
572
chaviw9eaa22c2020-07-01 16:21:27 -0700573 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800574 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800575 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700576 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
577 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700578 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
579 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700580 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800581 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700582 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800583 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800584 << "Should reject motion events with undefined action.";
585
586 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800587 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800588 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
589 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
590 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
591 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500592 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800593 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700594 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800595 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800596 << "Should reject motion events with pointer down index too large.";
597
Garfield Tanfbe732e2020-01-24 11:26:14 -0800598 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700599 AMOTION_EVENT_ACTION_POINTER_DOWN |
600 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700601 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
602 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700603 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500604 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800605 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700606 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800607 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800608 << "Should reject motion events with pointer down index too small.";
609
610 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800611 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800612 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
613 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
614 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
615 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500616 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800617 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700618 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800619 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800620 << "Should reject motion events with pointer up index too large.";
621
Garfield Tanfbe732e2020-01-24 11:26:14 -0800622 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700623 AMOTION_EVENT_ACTION_POINTER_UP |
624 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700625 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
626 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700627 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500628 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800629 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700630 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800631 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800632 << "Should reject motion events with pointer up index too small.";
633
634 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800635 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
636 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700637 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700638 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
639 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700640 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800641 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700642 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800643 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800644 << "Should reject motion events with 0 pointers.";
645
Garfield Tanfbe732e2020-01-24 11:26:14 -0800646 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
647 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700648 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700649 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
650 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700651 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800652 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700653 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800654 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655 << "Should reject motion events with more than MAX_POINTERS pointers.";
656
657 // Rejects motion events with invalid pointer ids.
658 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800659 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
660 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700661 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700662 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
663 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700664 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800665 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700666 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800667 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 << "Should reject motion events with pointer ids less than 0.";
669
670 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800671 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
672 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700673 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700674 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
675 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700676 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800677 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700678 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800679 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800680 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
681
682 // Rejects motion events with duplicate pointer ids.
683 pointerProperties[0].id = 1;
684 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800685 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
686 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700687 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700688 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
689 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700690 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800691 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700692 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800693 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800694 << "Should reject motion events with duplicate pointer ids.";
695}
696
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800697/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
698
699TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
700 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800701 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800702 mDispatcher->notifyConfigurationChanged(&args);
703 ASSERT_TRUE(mDispatcher->waitForIdle());
704
705 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
706}
707
708TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800709 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
710 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800711 mDispatcher->notifySwitch(&args);
712
713 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
714 args.policyFlags |= POLICY_FLAG_TRUSTED;
715 mFakePolicy->assertNotifySwitchWasCalled(args);
716}
717
Arthur Hungb92218b2018-08-14 12:00:21 +0800718// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700719static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700720// Default input dispatching timeout if there is no focused application or paused window
721// from which to determine an appropriate dispatching timeout.
722static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
723 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
724 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800725
726class FakeApplicationHandle : public InputApplicationHandle {
727public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700728 FakeApplicationHandle() {
729 mInfo.name = "Fake Application";
730 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500731 mInfo.dispatchingTimeoutMillis =
732 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700733 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800734 virtual ~FakeApplicationHandle() {}
735
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000736 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700737
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500738 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
739 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700740 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800741};
742
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800743class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800744public:
Garfield Tan15601662020-09-22 15:32:38 -0700745 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800746 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700747 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800748 }
749
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800750 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700751 InputEvent* event;
752 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
753 if (!consumeSeq) {
754 return nullptr;
755 }
756 finishEvent(*consumeSeq);
757 return event;
758 }
759
760 /**
761 * Receive an event without acknowledging it.
762 * Return the sequence number that could later be used to send finished signal.
763 */
764 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800765 uint32_t consumeSeq;
766 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800767
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800768 std::chrono::time_point start = std::chrono::steady_clock::now();
769 status_t status = WOULD_BLOCK;
770 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800771 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800772 &event);
773 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
774 if (elapsed > 100ms) {
775 break;
776 }
777 }
778
779 if (status == WOULD_BLOCK) {
780 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700781 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800782 }
783
784 if (status != OK) {
785 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700786 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800787 }
788 if (event == nullptr) {
789 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700790 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800791 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700792 if (outEvent != nullptr) {
793 *outEvent = event;
794 }
795 return consumeSeq;
796 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800797
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700798 /**
799 * To be used together with "receiveEvent" to complete the consumption of an event.
800 */
801 void finishEvent(uint32_t consumeSeq) {
802 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
803 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800804 }
805
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000806 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
807 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
808 ASSERT_EQ(OK, status);
809 }
810
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000811 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
812 std::optional<int32_t> expectedDisplayId,
813 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800814 InputEvent* event = consume();
815
816 ASSERT_NE(nullptr, event) << mName.c_str()
817 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800818 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700819 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800820 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800821
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000822 if (expectedDisplayId.has_value()) {
823 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
824 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800825
Tiger Huang8664f8c2018-10-11 19:14:35 +0800826 switch (expectedEventType) {
827 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800828 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
829 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000830 if (expectedFlags.has_value()) {
831 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
832 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800833 break;
834 }
835 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800836 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000837 assertMotionAction(expectedAction, motionEvent.getAction());
838
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000839 if (expectedFlags.has_value()) {
840 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
841 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800842 break;
843 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100844 case AINPUT_EVENT_TYPE_FOCUS: {
845 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
846 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800847 case AINPUT_EVENT_TYPE_CAPTURE: {
848 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
849 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000850 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
851 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
852 }
arthurhungb89ccb02020-12-30 16:19:01 +0800853 case AINPUT_EVENT_TYPE_DRAG: {
854 FAIL() << "Use 'consumeDragEvent' for DRAG events";
855 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800856 default: {
857 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
858 }
859 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800860 }
861
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100862 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
863 InputEvent* event = consume();
864 ASSERT_NE(nullptr, event) << mName.c_str()
865 << ": consumer should have returned non-NULL event.";
866 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
867 << "Got " << inputEventTypeToString(event->getType())
868 << " event instead of FOCUS event";
869
870 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
871 << mName.c_str() << ": event displayId should always be NONE.";
872
873 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
874 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100875 }
876
Prabir Pradhan99987712020-11-10 18:43:05 -0800877 void consumeCaptureEvent(bool hasCapture) {
878 const InputEvent* event = consume();
879 ASSERT_NE(nullptr, event) << mName.c_str()
880 << ": consumer should have returned non-NULL event.";
881 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
882 << "Got " << inputEventTypeToString(event->getType())
883 << " event instead of CAPTURE event";
884
885 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
886 << mName.c_str() << ": event displayId should always be NONE.";
887
888 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
889 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
890 }
891
arthurhungb89ccb02020-12-30 16:19:01 +0800892 void consumeDragEvent(bool isExiting, float x, float y) {
893 const InputEvent* event = consume();
894 ASSERT_NE(nullptr, event) << mName.c_str()
895 << ": consumer should have returned non-NULL event.";
896 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
897 << "Got " << inputEventTypeToString(event->getType())
898 << " event instead of DRAG event";
899
900 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
901 << mName.c_str() << ": event displayId should always be NONE.";
902
903 const auto& dragEvent = static_cast<const DragEvent&>(*event);
904 EXPECT_EQ(isExiting, dragEvent.isExiting());
905 EXPECT_EQ(x, dragEvent.getX());
906 EXPECT_EQ(y, dragEvent.getY());
907 }
908
Antonio Kantekf16f2832021-09-28 04:39:20 +0000909 void consumeTouchModeEvent(bool inTouchMode) {
910 const InputEvent* event = consume();
911 ASSERT_NE(nullptr, event) << mName.c_str()
912 << ": consumer should have returned non-NULL event.";
913 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
914 << "Got " << inputEventTypeToString(event->getType())
915 << " event instead of TOUCH_MODE event";
916
917 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
918 << mName.c_str() << ": event displayId should always be NONE.";
919 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
920 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
921 }
922
chaviwd1c23182019-12-20 18:44:56 -0800923 void assertNoEvents() {
924 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700925 if (event == nullptr) {
926 return;
927 }
928 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
929 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
930 ADD_FAILURE() << "Received key event "
931 << KeyEvent::actionToString(keyEvent.getAction());
932 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
933 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
934 ADD_FAILURE() << "Received motion event "
935 << MotionEvent::actionToString(motionEvent.getAction());
936 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
937 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
938 ADD_FAILURE() << "Received focus event, hasFocus = "
939 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800940 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
941 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
942 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
943 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000944 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
945 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
946 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
947 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700948 }
949 FAIL() << mName.c_str()
950 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800951 }
952
953 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
954
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800955 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
956
chaviwd1c23182019-12-20 18:44:56 -0800957protected:
958 std::unique_ptr<InputConsumer> mConsumer;
959 PreallocatedInputEventFactory mEventFactory;
960
961 std::string mName;
962};
963
chaviw3277faf2021-05-19 16:45:23 -0500964class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800965public:
966 static const int32_t WIDTH = 600;
967 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800968
Chris Yea209fde2020-07-22 13:54:51 -0700969 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700970 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500971 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800972 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500973 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700974 base::Result<std::unique_ptr<InputChannel>> channel =
975 dispatcher->createInputChannel(name);
976 token = (*channel)->getConnectionToken();
977 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800978 }
979
980 inputApplicationHandle->updateInfo();
981 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
982
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500983 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700984 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800985 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500986 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000987 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800988 mInfo.frameLeft = 0;
989 mInfo.frameTop = 0;
990 mInfo.frameRight = WIDTH;
991 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700992 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800993 mInfo.globalScaleFactor = 1.0;
994 mInfo.touchableRegion.clear();
995 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
chaviwd1c23182019-12-20 18:44:56 -0800996 mInfo.ownerPid = INJECTOR_PID;
997 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -0800998 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -0800999 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001000 }
1001
Arthur Hungabbb9d82021-09-01 14:52:30 +00001002 sp<FakeWindowHandle> clone(
1003 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001004 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001005 sp<FakeWindowHandle> handle =
1006 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1007 displayId, mInfo.token);
1008 return handle;
1009 }
1010
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001011 void setTouchable(bool touchable) {
1012 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1013 }
chaviwd1c23182019-12-20 18:44:56 -08001014
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001015 void setFocusable(bool focusable) {
1016 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1017 }
1018
1019 void setVisible(bool visible) {
1020 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1021 }
Vishnu Nair958da932020-08-21 17:12:37 -07001022
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001023 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001024 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001025 }
1026
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001027 void setPaused(bool paused) {
1028 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1029 }
1030
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001031 void setPreventSplitting(bool preventSplitting) {
1032 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001033 }
1034
1035 void setSlippery(bool slippery) {
1036 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1037 }
1038
1039 void setWatchOutsideTouch(bool watchOutside) {
1040 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1041 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001042
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001043 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1044
1045 void setInterceptsStylus(bool interceptsStylus) {
1046 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1047 }
1048
1049 void setDropInput(bool dropInput) {
1050 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1051 }
1052
1053 void setDropInputIfObscured(bool dropInputIfObscured) {
1054 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1055 }
1056
1057 void setNoInputChannel(bool noInputChannel) {
1058 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1059 }
1060
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001061 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1062
chaviw3277faf2021-05-19 16:45:23 -05001063 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001064
Bernardo Rufino7393d172021-02-26 13:56:11 +00001065 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1066
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001067 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001068 mInfo.frameLeft = frame.left;
1069 mInfo.frameTop = frame.top;
1070 mInfo.frameRight = frame.right;
1071 mInfo.frameBottom = frame.bottom;
1072 mInfo.touchableRegion.clear();
1073 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001074
1075 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1076 ui::Transform translate;
1077 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1078 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001079 }
1080
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001081 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1082
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001083 void setIsWallpaper(bool isWallpaper) {
1084 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1085 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001086
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001087 void setDupTouchToWallpaper(bool hasWallpaper) {
1088 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1089 }
chaviwd1c23182019-12-20 18:44:56 -08001090
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001091 void setTrustedOverlay(bool trustedOverlay) {
1092 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1093 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001094
chaviw9eaa22c2020-07-01 16:21:27 -07001095 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1096 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1097 }
1098
1099 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001100
yunho.shinf4a80b82020-11-16 21:13:57 +09001101 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1102
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001103 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1104 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1105 expectedFlags);
1106 }
1107
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001108 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1109 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1110 }
1111
Svet Ganov5d3bc372020-01-26 23:11:07 -08001112 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001113 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001114 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1115 expectedFlags);
1116 }
1117
1118 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001119 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001120 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1121 expectedFlags);
1122 }
1123
1124 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001125 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001126 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1127 }
1128
1129 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1130 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001131 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1132 expectedFlags);
1133 }
1134
Svet Ganov5d3bc372020-01-26 23:11:07 -08001135 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001136 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1137 int32_t expectedFlags = 0) {
1138 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1139 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001140 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1141 }
1142
1143 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001144 int32_t expectedFlags = 0) {
1145 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1146 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001147 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1148 }
1149
1150 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001151 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001152 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1153 expectedFlags);
1154 }
1155
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001156 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1157 int32_t expectedFlags = 0) {
1158 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1159 expectedFlags);
1160 }
1161
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001162 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1163 int32_t expectedFlags = 0) {
1164 InputEvent* event = consume();
1165 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1166 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1167 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1168 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1169 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1170 }
1171
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001172 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1173 ASSERT_NE(mInputReceiver, nullptr)
1174 << "Cannot consume events from a window with no receiver";
1175 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1176 }
1177
Prabir Pradhan99987712020-11-10 18:43:05 -08001178 void consumeCaptureEvent(bool hasCapture) {
1179 ASSERT_NE(mInputReceiver, nullptr)
1180 << "Cannot consume events from a window with no receiver";
1181 mInputReceiver->consumeCaptureEvent(hasCapture);
1182 }
1183
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001184 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1185 std::optional<int32_t> expectedDisplayId,
1186 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001187 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1188 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1189 expectedFlags);
1190 }
1191
arthurhungb89ccb02020-12-30 16:19:01 +08001192 void consumeDragEvent(bool isExiting, float x, float y) {
1193 mInputReceiver->consumeDragEvent(isExiting, x, y);
1194 }
1195
Antonio Kantekf16f2832021-09-28 04:39:20 +00001196 void consumeTouchModeEvent(bool inTouchMode) {
1197 ASSERT_NE(mInputReceiver, nullptr)
1198 << "Cannot consume events from a window with no receiver";
1199 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1200 }
1201
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001202 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001203 if (mInputReceiver == nullptr) {
1204 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1205 return std::nullopt;
1206 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001207 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001208 }
1209
1210 void finishEvent(uint32_t sequenceNum) {
1211 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1212 mInputReceiver->finishEvent(sequenceNum);
1213 }
1214
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001215 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1216 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1217 mInputReceiver->sendTimeline(inputEventId, timeline);
1218 }
1219
chaviwaf87b3e2019-10-01 16:59:28 -07001220 InputEvent* consume() {
1221 if (mInputReceiver == nullptr) {
1222 return nullptr;
1223 }
1224 return mInputReceiver->consume();
1225 }
1226
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001227 MotionEvent* consumeMotion() {
1228 InputEvent* event = consume();
1229 if (event == nullptr) {
1230 ADD_FAILURE() << "Consume failed : no event";
1231 return nullptr;
1232 }
1233 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1234 ADD_FAILURE() << "Instead of motion event, got "
1235 << inputEventTypeToString(event->getType());
1236 return nullptr;
1237 }
1238 return static_cast<MotionEvent*>(event);
1239 }
1240
Arthur Hungb92218b2018-08-14 12:00:21 +08001241 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001242 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001243 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001244 return; // Can't receive events if the window does not have input channel
1245 }
1246 ASSERT_NE(nullptr, mInputReceiver)
1247 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001248 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001249 }
1250
chaviwaf87b3e2019-10-01 16:59:28 -07001251 sp<IBinder> getToken() { return mInfo.token; }
1252
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001253 const std::string& getName() { return mName; }
1254
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001255 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1256 mInfo.ownerPid = ownerPid;
1257 mInfo.ownerUid = ownerUid;
1258 }
1259
Prabir Pradhanedd96402022-02-15 01:46:16 -08001260 int32_t getPid() const { return mInfo.ownerPid; }
1261
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001262 void destroyReceiver() { mInputReceiver = nullptr; }
1263
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001264 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1265
chaviwd1c23182019-12-20 18:44:56 -08001266private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001267 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001268 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001269 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001270};
1271
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001272std::atomic<int32_t> FakeWindowHandle::sId{1};
1273
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001274static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001275 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001276 int32_t displayId = ADISPLAY_ID_NONE,
1277 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001278 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1279 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001280 KeyEvent event;
1281 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1282
1283 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001284 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001285 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1286 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001287
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001288 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1289 if (!allowKeyRepeat) {
1290 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1291 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001292 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001293 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001294 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001295}
1296
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001297static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001298 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001299 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1300}
1301
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001302// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1303// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1304// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001305static InputEventInjectionResult injectKeyDownNoRepeat(
1306 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001307 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1308 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1309 /* allowKeyRepeat */ false);
1310}
1311
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001312static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001313 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001314 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1315}
1316
Garfield Tandf26e862020-07-01 20:18:19 -07001317class PointerBuilder {
1318public:
1319 PointerBuilder(int32_t id, int32_t toolType) {
1320 mProperties.clear();
1321 mProperties.id = id;
1322 mProperties.toolType = toolType;
1323 mCoords.clear();
1324 }
1325
1326 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1327
1328 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1329
1330 PointerBuilder& axis(int32_t axis, float value) {
1331 mCoords.setAxisValue(axis, value);
1332 return *this;
1333 }
1334
1335 PointerProperties buildProperties() const { return mProperties; }
1336
1337 PointerCoords buildCoords() const { return mCoords; }
1338
1339private:
1340 PointerProperties mProperties;
1341 PointerCoords mCoords;
1342};
1343
1344class MotionEventBuilder {
1345public:
1346 MotionEventBuilder(int32_t action, int32_t source) {
1347 mAction = action;
1348 mSource = source;
1349 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1350 }
1351
1352 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1353 mEventTime = eventTime;
1354 return *this;
1355 }
1356
1357 MotionEventBuilder& displayId(int32_t displayId) {
1358 mDisplayId = displayId;
1359 return *this;
1360 }
1361
1362 MotionEventBuilder& actionButton(int32_t actionButton) {
1363 mActionButton = actionButton;
1364 return *this;
1365 }
1366
arthurhung6d4bed92021-03-17 11:59:33 +08001367 MotionEventBuilder& buttonState(int32_t buttonState) {
1368 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001369 return *this;
1370 }
1371
1372 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1373 mRawXCursorPosition = rawXCursorPosition;
1374 return *this;
1375 }
1376
1377 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1378 mRawYCursorPosition = rawYCursorPosition;
1379 return *this;
1380 }
1381
1382 MotionEventBuilder& pointer(PointerBuilder pointer) {
1383 mPointers.push_back(pointer);
1384 return *this;
1385 }
1386
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001387 MotionEventBuilder& addFlag(uint32_t flags) {
1388 mFlags |= flags;
1389 return *this;
1390 }
1391
Garfield Tandf26e862020-07-01 20:18:19 -07001392 MotionEvent build() {
1393 std::vector<PointerProperties> pointerProperties;
1394 std::vector<PointerCoords> pointerCoords;
1395 for (const PointerBuilder& pointer : mPointers) {
1396 pointerProperties.push_back(pointer.buildProperties());
1397 pointerCoords.push_back(pointer.buildCoords());
1398 }
1399
1400 // Set mouse cursor position for the most common cases to avoid boilerplate.
1401 if (mSource == AINPUT_SOURCE_MOUSE &&
1402 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1403 mPointers.size() == 1) {
1404 mRawXCursorPosition = pointerCoords[0].getX();
1405 mRawYCursorPosition = pointerCoords[0].getY();
1406 }
1407
1408 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001409 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001410 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001411 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001412 mButtonState, MotionClassification::NONE, identityTransform,
1413 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001414 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1415 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001416
1417 return event;
1418 }
1419
1420private:
1421 int32_t mAction;
1422 int32_t mSource;
1423 nsecs_t mEventTime;
1424 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1425 int32_t mActionButton{0};
1426 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001427 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001428 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1429 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1430
1431 std::vector<PointerBuilder> mPointers;
1432};
1433
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001434static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001435 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001436 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001437 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001438 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1439 injectionTimeout,
1440 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1441}
1442
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001443static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001444 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001445 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001446 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001447 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1448 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001449 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001450 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001451 MotionEvent event = MotionEventBuilder(action, source)
1452 .displayId(displayId)
1453 .eventTime(eventTime)
1454 .rawXCursorPosition(cursorPosition.x)
1455 .rawYCursorPosition(cursorPosition.y)
1456 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1457 .x(position.x)
1458 .y(position.y))
1459 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001460
1461 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001462 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001463}
1464
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001465static InputEventInjectionResult injectMotionDown(
1466 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1467 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001468 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001469}
1470
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001471static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001472 int32_t source, int32_t displayId,
1473 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001474 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001475}
1476
Jackal Guof9696682018-10-05 12:23:23 +08001477static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1478 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1479 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001480 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1481 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1482 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001483
1484 return args;
1485}
1486
chaviwd1c23182019-12-20 18:44:56 -08001487static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1488 const std::vector<PointF>& points) {
1489 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001490 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1491 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1492 }
1493
chaviwd1c23182019-12-20 18:44:56 -08001494 PointerProperties pointerProperties[pointerCount];
1495 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001496
chaviwd1c23182019-12-20 18:44:56 -08001497 for (size_t i = 0; i < pointerCount; i++) {
1498 pointerProperties[i].clear();
1499 pointerProperties[i].id = i;
1500 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001501
chaviwd1c23182019-12-20 18:44:56 -08001502 pointerCoords[i].clear();
1503 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1504 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1505 }
Jackal Guof9696682018-10-05 12:23:23 +08001506
1507 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1508 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001509 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001510 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1511 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001512 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1513 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001514 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1515 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001516
1517 return args;
1518}
1519
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001520static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1521 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1522}
1523
chaviwd1c23182019-12-20 18:44:56 -08001524static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1525 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1526}
1527
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001528static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1529 const PointerCaptureRequest& request) {
1530 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001531}
1532
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001533/**
1534 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1535 * broken channel.
1536 */
1537TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1538 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1539 sp<FakeWindowHandle> window =
1540 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1541 ADISPLAY_ID_DEFAULT);
1542
1543 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1544
1545 // Window closes its channel, but the window remains.
1546 window->destroyReceiver();
1547 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1548}
1549
Arthur Hungb92218b2018-08-14 12:00:21 +08001550TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001551 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001552 sp<FakeWindowHandle> window =
1553 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001554
Arthur Hung72d8dc32020-03-28 00:48:39 +00001555 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001556 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1557 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1558 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001559
1560 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001561 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001562}
1563
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001564TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1565 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1566 sp<FakeWindowHandle> window =
1567 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1568
1569 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1570 // Inject a MotionEvent to an unknown display.
1571 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1572 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1573 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1574
1575 // Window should receive motion event.
1576 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1577}
1578
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001579/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001580 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001581 * This test serves as a sanity check for the next test, where setInputWindows is
1582 * called twice.
1583 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001584TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001585 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001586 sp<FakeWindowHandle> window =
1587 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1588 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001589
1590 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001591 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001592 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1593 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001594 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001595
1596 // Window should receive motion event.
1597 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1598}
1599
1600/**
1601 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001602 */
1603TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001604 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001605 sp<FakeWindowHandle> window =
1606 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1607 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001608
1609 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1610 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001611 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001612 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1613 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001614 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001615
1616 // Window should receive motion event.
1617 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1618}
1619
Arthur Hungb92218b2018-08-14 12:00:21 +08001620// The foreground window should receive the first touch down event.
1621TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001622 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001623 sp<FakeWindowHandle> windowTop =
1624 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1625 sp<FakeWindowHandle> windowSecond =
1626 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001627
Arthur Hung72d8dc32020-03-28 00:48:39 +00001628 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001629 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1630 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1631 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001632
1633 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001634 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001635 windowSecond->assertNoEvents();
1636}
1637
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001638/**
1639 * Two windows: A top window, and a wallpaper behind the window.
1640 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1641 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001642 * 1. foregroundWindow <-- dup touch to wallpaper
1643 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001644 */
1645TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1646 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1647 sp<FakeWindowHandle> foregroundWindow =
1648 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001649 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001650 sp<FakeWindowHandle> wallpaperWindow =
1651 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001652 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001653 constexpr int expectedWallpaperFlags =
1654 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1655
1656 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1657 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1658 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1659 {100, 200}))
1660 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1661
1662 // Both foreground window and its wallpaper should receive the touch down
1663 foregroundWindow->consumeMotionDown();
1664 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1665
1666 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1667 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1668 ADISPLAY_ID_DEFAULT, {110, 200}))
1669 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1670
1671 foregroundWindow->consumeMotionMove();
1672 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1673
1674 // Now the foreground window goes away, but the wallpaper stays
1675 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1676 foregroundWindow->consumeMotionCancel();
1677 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1678 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1679}
1680
1681/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001682 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1683 * with the following differences:
1684 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1685 * clean up the connection.
1686 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1687 * Ensure that there's no crash in the dispatcher.
1688 */
1689TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1690 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1691 sp<FakeWindowHandle> foregroundWindow =
1692 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001693 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001694 sp<FakeWindowHandle> wallpaperWindow =
1695 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001696 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001697 constexpr int expectedWallpaperFlags =
1698 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1699
1700 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1701 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1702 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1703 {100, 200}))
1704 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1705
1706 // Both foreground window and its wallpaper should receive the touch down
1707 foregroundWindow->consumeMotionDown();
1708 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1709
1710 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1711 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1712 ADISPLAY_ID_DEFAULT, {110, 200}))
1713 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1714
1715 foregroundWindow->consumeMotionMove();
1716 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1717
1718 // Wallpaper closes its channel, but the window remains.
1719 wallpaperWindow->destroyReceiver();
1720 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1721
1722 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1723 // is no longer valid.
1724 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1725 foregroundWindow->consumeMotionCancel();
1726}
1727
1728/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001729 * A single window that receives touch (on top), and a wallpaper window underneath it.
1730 * The top window gets a multitouch gesture.
1731 * Ensure that wallpaper gets the same gesture.
1732 */
1733TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1734 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1735 sp<FakeWindowHandle> window =
1736 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001737 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001738
1739 sp<FakeWindowHandle> wallpaperWindow =
1740 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001741 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001742 constexpr int expectedWallpaperFlags =
1743 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1744
1745 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1746
1747 // Touch down on top window
1748 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1749 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1750 {100, 100}))
1751 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1752
1753 // Both top window and its wallpaper should receive the touch down
1754 window->consumeMotionDown();
1755 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1756
1757 // Second finger down on the top window
1758 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001759 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001760 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1761 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1762 .x(100)
1763 .y(100))
1764 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1765 .x(150)
1766 .y(150))
1767 .build();
1768 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1769 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1770 InputEventInjectionSync::WAIT_FOR_RESULT))
1771 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1772
1773 window->consumeMotionPointerDown(1 /* pointerIndex */);
1774 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1775 expectedWallpaperFlags);
1776 window->assertNoEvents();
1777 wallpaperWindow->assertNoEvents();
1778}
1779
1780/**
1781 * Two windows: a window on the left and window on the right.
1782 * A third window, wallpaper, is behind both windows, and spans both top windows.
1783 * The first touch down goes to the left window. A second pointer touches down on the right window.
1784 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1785 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1786 * ACTION_POINTER_DOWN(1).
1787 */
1788TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1789 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1790 sp<FakeWindowHandle> leftWindow =
1791 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1792 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001793 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001794
1795 sp<FakeWindowHandle> rightWindow =
1796 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1797 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001798 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001799
1800 sp<FakeWindowHandle> wallpaperWindow =
1801 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1802 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001803 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001804 constexpr int expectedWallpaperFlags =
1805 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1806
1807 mDispatcher->setInputWindows(
1808 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1809
1810 // Touch down on left window
1811 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1812 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1813 {100, 100}))
1814 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1815
1816 // Both foreground window and its wallpaper should receive the touch down
1817 leftWindow->consumeMotionDown();
1818 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1819
1820 // Second finger down on the right window
1821 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001822 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001823 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1824 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1825 .x(100)
1826 .y(100))
1827 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1828 .x(300)
1829 .y(100))
1830 .build();
1831 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1832 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1833 InputEventInjectionSync::WAIT_FOR_RESULT))
1834 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1835
1836 leftWindow->consumeMotionMove();
1837 // Since the touch is split, right window gets ACTION_DOWN
1838 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1839 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1840 expectedWallpaperFlags);
1841
1842 // Now, leftWindow, which received the first finger, disappears.
1843 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1844 leftWindow->consumeMotionCancel();
1845 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1846 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1847
1848 // The pointer that's still down on the right window moves, and goes to the right window only.
1849 // As far as the dispatcher's concerned though, both pointers are still present.
1850 const MotionEvent secondFingerMoveEvent =
1851 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1852 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1853 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1854 .x(100)
1855 .y(100))
1856 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1857 .x(310)
1858 .y(110))
1859 .build();
1860 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1861 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1862 InputEventInjectionSync::WAIT_FOR_RESULT));
1863 rightWindow->consumeMotionMove();
1864
1865 leftWindow->assertNoEvents();
1866 rightWindow->assertNoEvents();
1867 wallpaperWindow->assertNoEvents();
1868}
1869
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001870/**
1871 * On the display, have a single window, and also an area where there's no window.
1872 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
1873 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
1874 */
1875TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
1876 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1877 sp<FakeWindowHandle> window =
1878 new FakeWindowHandle(application, mDispatcher, "Window", DISPLAY_ID);
1879
1880 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
1881 NotifyMotionArgs args;
1882
1883 // Touch down on the empty space
1884 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
1885
1886 mDispatcher->waitForIdle();
1887 window->assertNoEvents();
1888
1889 // Now touch down on the window with another pointer
1890 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
1891 mDispatcher->waitForIdle();
1892 window->consumeMotionDown();
1893}
1894
1895/**
1896 * Same test as above, but instead of touching the empty space, the first touch goes to
1897 * non-touchable window.
1898 */
1899TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
1900 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1901 sp<FakeWindowHandle> window1 =
1902 new FakeWindowHandle(application, mDispatcher, "Window1", DISPLAY_ID);
1903 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1904 window1->setTouchable(false);
1905 sp<FakeWindowHandle> window2 =
1906 new FakeWindowHandle(application, mDispatcher, "Window2", DISPLAY_ID);
1907 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1908
1909 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1910
1911 NotifyMotionArgs args;
1912 // Touch down on the non-touchable window
1913 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1914
1915 mDispatcher->waitForIdle();
1916 window1->assertNoEvents();
1917 window2->assertNoEvents();
1918
1919 // Now touch down on the window with another pointer
1920 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1921 mDispatcher->waitForIdle();
1922 window2->consumeMotionDown();
1923}
1924
Garfield Tandf26e862020-07-01 20:18:19 -07001925TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001926 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001927 sp<FakeWindowHandle> windowLeft =
1928 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1929 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001930 sp<FakeWindowHandle> windowRight =
1931 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1932 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001933
1934 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1935
1936 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1937
1938 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001939 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001940 injectMotionEvent(mDispatcher,
1941 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1942 AINPUT_SOURCE_MOUSE)
1943 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1944 .x(900)
1945 .y(400))
1946 .build()));
1947 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1948 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1949 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1950 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1951
1952 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001953 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001954 injectMotionEvent(mDispatcher,
1955 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1956 AINPUT_SOURCE_MOUSE)
1957 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1958 .x(300)
1959 .y(400))
1960 .build()));
1961 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1962 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1963 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1964 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1965 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1966 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1967
1968 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001970 injectMotionEvent(mDispatcher,
1971 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1972 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1973 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1974 .x(300)
1975 .y(400))
1976 .build()));
1977 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1978
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001979 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001980 injectMotionEvent(mDispatcher,
1981 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1982 AINPUT_SOURCE_MOUSE)
1983 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1984 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1985 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1986 .x(300)
1987 .y(400))
1988 .build()));
1989 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1990 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1991
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001992 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001993 injectMotionEvent(mDispatcher,
1994 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1995 AINPUT_SOURCE_MOUSE)
1996 .buttonState(0)
1997 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1998 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1999 .x(300)
2000 .y(400))
2001 .build()));
2002 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2003 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2004
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002005 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002006 injectMotionEvent(mDispatcher,
2007 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2008 .buttonState(0)
2009 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2010 .x(300)
2011 .y(400))
2012 .build()));
2013 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2014
2015 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002016 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002017 injectMotionEvent(mDispatcher,
2018 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2019 AINPUT_SOURCE_MOUSE)
2020 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2021 .x(900)
2022 .y(400))
2023 .build()));
2024 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2025 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2026 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2027 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2028 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2029 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2030}
2031
2032// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2033// directly in this test.
2034TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002035 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002036 sp<FakeWindowHandle> window =
2037 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2038 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002039
2040 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2041
2042 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2043
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002044 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002045 injectMotionEvent(mDispatcher,
2046 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2047 AINPUT_SOURCE_MOUSE)
2048 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2049 .x(300)
2050 .y(400))
2051 .build()));
2052 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2053 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2054
2055 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002056 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002057 injectMotionEvent(mDispatcher,
2058 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2059 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2060 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2061 .x(300)
2062 .y(400))
2063 .build()));
2064 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2065
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002066 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002067 injectMotionEvent(mDispatcher,
2068 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2069 AINPUT_SOURCE_MOUSE)
2070 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2071 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2072 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2073 .x(300)
2074 .y(400))
2075 .build()));
2076 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2077 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2078
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002079 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002080 injectMotionEvent(mDispatcher,
2081 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2082 AINPUT_SOURCE_MOUSE)
2083 .buttonState(0)
2084 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2085 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2086 .x(300)
2087 .y(400))
2088 .build()));
2089 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2090 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2091
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002092 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002093 injectMotionEvent(mDispatcher,
2094 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2095 .buttonState(0)
2096 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2097 .x(300)
2098 .y(400))
2099 .build()));
2100 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2101
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002102 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002103 injectMotionEvent(mDispatcher,
2104 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2105 AINPUT_SOURCE_MOUSE)
2106 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2107 .x(300)
2108 .y(400))
2109 .build()));
2110 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2111 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2112}
2113
Garfield Tan00f511d2019-06-12 16:55:40 -07002114TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002115 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002116
2117 sp<FakeWindowHandle> windowLeft =
2118 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2119 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002120 sp<FakeWindowHandle> windowRight =
2121 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2122 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002123
2124 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2125
Arthur Hung72d8dc32020-03-28 00:48:39 +00002126 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002127
2128 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2129 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002130 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002131 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002132 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002133 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002134 windowRight->assertNoEvents();
2135}
2136
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002137TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002138 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002139 sp<FakeWindowHandle> window =
2140 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002141 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002142
Arthur Hung72d8dc32020-03-28 00:48:39 +00002143 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002144 setFocusedWindow(window);
2145
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002146 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002147
2148 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2149 mDispatcher->notifyKey(&keyArgs);
2150
2151 // Window should receive key down event.
2152 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2153
2154 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2155 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002156 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002157 mDispatcher->notifyDeviceReset(&args);
2158 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2159 AKEY_EVENT_FLAG_CANCELED);
2160}
2161
2162TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002163 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002164 sp<FakeWindowHandle> window =
2165 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2166
Arthur Hung72d8dc32020-03-28 00:48:39 +00002167 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002168
2169 NotifyMotionArgs motionArgs =
2170 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2171 ADISPLAY_ID_DEFAULT);
2172 mDispatcher->notifyMotion(&motionArgs);
2173
2174 // Window should receive motion down event.
2175 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2176
2177 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2178 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002179 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002180 mDispatcher->notifyDeviceReset(&args);
2181 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2182 0 /*expectedFlags*/);
2183}
2184
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002185/**
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00002186 * This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
2187 * a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
2188 * ACTION_OUTSIDE event is sent per gesture.
2189 */
2190TEST_F(InputDispatcherTest, ActionOutsideSentOnlyWhenAWindowIsTouched) {
2191 // There are three windows that do not overlap. `window` wants to WATCH_OUTSIDE_TOUCH.
2192 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2193 sp<FakeWindowHandle> window =
2194 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2195 window->setWatchOutsideTouch(true);
2196 window->setFrame(Rect{0, 0, 100, 100});
2197 sp<FakeWindowHandle> secondWindow =
2198 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2199 secondWindow->setFrame(Rect{100, 100, 200, 200});
2200 sp<FakeWindowHandle> thirdWindow =
2201 new FakeWindowHandle(application, mDispatcher, "Third Window", ADISPLAY_ID_DEFAULT);
2202 thirdWindow->setFrame(Rect{200, 200, 300, 300});
2203 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, secondWindow, thirdWindow}}});
2204
2205 // First pointer lands outside all windows. `window` does not get ACTION_OUTSIDE.
2206 NotifyMotionArgs motionArgs =
2207 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2208 ADISPLAY_ID_DEFAULT, {PointF{-10, -10}});
2209 mDispatcher->notifyMotion(&motionArgs);
2210 window->assertNoEvents();
2211 secondWindow->assertNoEvents();
2212
2213 // The second pointer lands inside `secondWindow`, which should receive a DOWN event.
2214 // Now, `window` should get ACTION_OUTSIDE.
2215 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2216 {PointF{-10, -10}, PointF{105, 105}});
2217 mDispatcher->notifyMotion(&motionArgs);
2218 window->consumeMotionOutside();
2219 secondWindow->consumeMotionDown();
2220 thirdWindow->assertNoEvents();
2221
2222 // The third pointer lands inside `thirdWindow`, which should receive a DOWN event. There is
2223 // no ACTION_OUTSIDE sent to `window` because one has already been sent for this gesture.
2224 motionArgs = generateMotionArgs(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2225 {PointF{-10, -10}, PointF{105, 105}, PointF{205, 205}});
2226 mDispatcher->notifyMotion(&motionArgs);
2227 window->assertNoEvents();
2228 secondWindow->consumeMotionMove();
2229 thirdWindow->consumeMotionDown();
2230}
2231
2232/**
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002233 * Ensure the correct coordinate spaces are used by InputDispatcher.
2234 *
2235 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2236 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2237 * space.
2238 */
2239class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2240public:
2241 void SetUp() override {
2242 InputDispatcherTest::SetUp();
2243 mDisplayInfos.clear();
2244 mWindowInfos.clear();
2245 }
2246
2247 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2248 gui::DisplayInfo info;
2249 info.displayId = displayId;
2250 info.transform = transform;
2251 mDisplayInfos.push_back(std::move(info));
2252 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2253 }
2254
2255 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2256 mWindowInfos.push_back(*windowHandle->getInfo());
2257 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2258 }
2259
2260 // Set up a test scenario where the display has a scaled projection and there are two windows
2261 // on the display.
2262 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2263 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2264 // respectively.
2265 ui::Transform displayTransform;
2266 displayTransform.set(2, 0, 0, 4);
2267 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2268
2269 std::shared_ptr<FakeApplicationHandle> application =
2270 std::make_shared<FakeApplicationHandle>();
2271
2272 // Add two windows to the display. Their frames are represented in the display space.
2273 sp<FakeWindowHandle> firstWindow =
2274 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002275 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2276 addWindow(firstWindow);
2277
2278 sp<FakeWindowHandle> secondWindow =
2279 new FakeWindowHandle(application, mDispatcher, "Second Window",
2280 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002281 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2282 addWindow(secondWindow);
2283 return {std::move(firstWindow), std::move(secondWindow)};
2284 }
2285
2286private:
2287 std::vector<gui::DisplayInfo> mDisplayInfos;
2288 std::vector<gui::WindowInfo> mWindowInfos;
2289};
2290
2291TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2292 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2293 // Send down to the first window. The point is represented in the display space. The point is
2294 // selected so that if the hit test was done with the transform applied to it, then it would
2295 // end up in the incorrect window.
2296 NotifyMotionArgs downMotionArgs =
2297 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2298 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2299 mDispatcher->notifyMotion(&downMotionArgs);
2300
2301 firstWindow->consumeMotionDown();
2302 secondWindow->assertNoEvents();
2303}
2304
2305// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2306// the event should be treated as being in the logical display space.
2307TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2308 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2309 // Send down to the first window. The point is represented in the logical display space. The
2310 // point is selected so that if the hit test was done in logical display space, then it would
2311 // end up in the incorrect window.
2312 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2313 PointF{75 * 2, 55 * 4});
2314
2315 firstWindow->consumeMotionDown();
2316 secondWindow->assertNoEvents();
2317}
2318
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002319// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2320// event should be treated as being in the logical display space.
2321TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2322 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2323
2324 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2325 ui::Transform injectedEventTransform;
2326 injectedEventTransform.set(matrix);
2327 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2328 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2329
2330 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2331 .displayId(ADISPLAY_ID_DEFAULT)
2332 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2333 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2334 .x(untransformedPoint.x)
2335 .y(untransformedPoint.y))
2336 .build();
2337 event.transform(matrix);
2338
2339 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2340 InputEventInjectionSync::WAIT_FOR_RESULT);
2341
2342 firstWindow->consumeMotionDown();
2343 secondWindow->assertNoEvents();
2344}
2345
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002346TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2347 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2348
2349 // Send down to the second window.
2350 NotifyMotionArgs downMotionArgs =
2351 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2352 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2353 mDispatcher->notifyMotion(&downMotionArgs);
2354
2355 firstWindow->assertNoEvents();
2356 const MotionEvent* event = secondWindow->consumeMotion();
2357 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2358
2359 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2360 EXPECT_EQ(300, event->getRawX(0));
2361 EXPECT_EQ(880, event->getRawY(0));
2362
2363 // Ensure that the x and y values are in the window's coordinate space.
2364 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2365 // the logical display space. This will be the origin of the window space.
2366 EXPECT_EQ(100, event->getX(0));
2367 EXPECT_EQ(80, event->getY(0));
2368}
2369
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002370using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2371 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002372
2373class TransferTouchFixture : public InputDispatcherTest,
2374 public ::testing::WithParamInterface<TransferFunction> {};
2375
2376TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002377 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002378
2379 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002380 sp<FakeWindowHandle> firstWindow =
2381 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2382 sp<FakeWindowHandle> secondWindow =
2383 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002384
2385 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002386 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002387
2388 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002389 NotifyMotionArgs downMotionArgs =
2390 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2391 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002392 mDispatcher->notifyMotion(&downMotionArgs);
2393 // Only the first window should get the down event
2394 firstWindow->consumeMotionDown();
2395 secondWindow->assertNoEvents();
2396
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002397 // Transfer touch to the second window
2398 TransferFunction f = GetParam();
2399 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2400 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002401 // The first window gets cancel and the second gets down
2402 firstWindow->consumeMotionCancel();
2403 secondWindow->consumeMotionDown();
2404
2405 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002406 NotifyMotionArgs upMotionArgs =
2407 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2408 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002409 mDispatcher->notifyMotion(&upMotionArgs);
2410 // The first window gets no events and the second gets up
2411 firstWindow->assertNoEvents();
2412 secondWindow->consumeMotionUp();
2413}
2414
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002415TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002416 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002417
2418 PointF touchPoint = {10, 10};
2419
2420 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002421 sp<FakeWindowHandle> firstWindow =
2422 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002423 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002424 sp<FakeWindowHandle> secondWindow =
2425 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002426 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002427
2428 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002429 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002430
2431 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002432 NotifyMotionArgs downMotionArgs =
2433 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2434 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002435 mDispatcher->notifyMotion(&downMotionArgs);
2436 // Only the first window should get the down event
2437 firstWindow->consumeMotionDown();
2438 secondWindow->assertNoEvents();
2439
2440 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002441 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002442 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002443 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002444 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2445 // Only the first window should get the pointer down event
2446 firstWindow->consumeMotionPointerDown(1);
2447 secondWindow->assertNoEvents();
2448
2449 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002450 TransferFunction f = GetParam();
2451 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2452 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002453 // The first window gets cancel and the second gets down and pointer down
2454 firstWindow->consumeMotionCancel();
2455 secondWindow->consumeMotionDown();
2456 secondWindow->consumeMotionPointerDown(1);
2457
2458 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002459 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002460 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002461 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002462 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2463 // The first window gets nothing and the second gets pointer up
2464 firstWindow->assertNoEvents();
2465 secondWindow->consumeMotionPointerUp(1);
2466
2467 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002468 NotifyMotionArgs upMotionArgs =
2469 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2470 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002471 mDispatcher->notifyMotion(&upMotionArgs);
2472 // The first window gets nothing and the second gets up
2473 firstWindow->assertNoEvents();
2474 secondWindow->consumeMotionUp();
2475}
2476
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002477// For the cases of single pointer touch and two pointers non-split touch, the api's
2478// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2479// for the case where there are multiple pointers split across several windows.
2480INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2481 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002482 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2483 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002484 return dispatcher->transferTouch(destChannelToken);
2485 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002486 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2487 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002488 return dispatcher->transferTouchFocus(from, to,
2489 false /*isDragAndDrop*/);
2490 }));
2491
Svet Ganov5d3bc372020-01-26 23:11:07 -08002492TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002493 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002494
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002495 sp<FakeWindowHandle> firstWindow =
2496 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002497 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002498
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002499 sp<FakeWindowHandle> secondWindow =
2500 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002501 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002502
2503 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002504 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002505
2506 PointF pointInFirst = {300, 200};
2507 PointF pointInSecond = {300, 600};
2508
2509 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002510 NotifyMotionArgs firstDownMotionArgs =
2511 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2512 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002513 mDispatcher->notifyMotion(&firstDownMotionArgs);
2514 // Only the first window should get the down event
2515 firstWindow->consumeMotionDown();
2516 secondWindow->assertNoEvents();
2517
2518 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002519 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002520 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002521 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002522 mDispatcher->notifyMotion(&secondDownMotionArgs);
2523 // The first window gets a move and the second a down
2524 firstWindow->consumeMotionMove();
2525 secondWindow->consumeMotionDown();
2526
2527 // Transfer touch focus to the second window
2528 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2529 // The first window gets cancel and the new gets pointer down (it already saw down)
2530 firstWindow->consumeMotionCancel();
2531 secondWindow->consumeMotionPointerDown(1);
2532
2533 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002534 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002535 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002536 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002537 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2538 // The first window gets nothing and the second gets pointer up
2539 firstWindow->assertNoEvents();
2540 secondWindow->consumeMotionPointerUp(1);
2541
2542 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002543 NotifyMotionArgs upMotionArgs =
2544 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2545 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002546 mDispatcher->notifyMotion(&upMotionArgs);
2547 // The first window gets nothing and the second gets up
2548 firstWindow->assertNoEvents();
2549 secondWindow->consumeMotionUp();
2550}
2551
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002552// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2553// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2554// touch is not supported, so the touch should continue on those windows and the transferred-to
2555// window should get nothing.
2556TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2557 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2558
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002559 sp<FakeWindowHandle> firstWindow =
2560 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2561 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002562
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002563 sp<FakeWindowHandle> secondWindow =
2564 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2565 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002566
2567 // Add the windows to the dispatcher
2568 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2569
2570 PointF pointInFirst = {300, 200};
2571 PointF pointInSecond = {300, 600};
2572
2573 // Send down to the first window
2574 NotifyMotionArgs firstDownMotionArgs =
2575 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2576 ADISPLAY_ID_DEFAULT, {pointInFirst});
2577 mDispatcher->notifyMotion(&firstDownMotionArgs);
2578 // Only the first window should get the down event
2579 firstWindow->consumeMotionDown();
2580 secondWindow->assertNoEvents();
2581
2582 // Send down to the second window
2583 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002584 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002585 {pointInFirst, pointInSecond});
2586 mDispatcher->notifyMotion(&secondDownMotionArgs);
2587 // The first window gets a move and the second a down
2588 firstWindow->consumeMotionMove();
2589 secondWindow->consumeMotionDown();
2590
2591 // Transfer touch focus to the second window
2592 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2593 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2594 ASSERT_FALSE(transferred);
2595 firstWindow->assertNoEvents();
2596 secondWindow->assertNoEvents();
2597
2598 // The rest of the dispatch should proceed as normal
2599 // Send pointer up to the second window
2600 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002601 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002602 {pointInFirst, pointInSecond});
2603 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2604 // The first window gets MOVE and the second gets pointer up
2605 firstWindow->consumeMotionMove();
2606 secondWindow->consumeMotionUp();
2607
2608 // Send up event to the first window
2609 NotifyMotionArgs upMotionArgs =
2610 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2611 ADISPLAY_ID_DEFAULT);
2612 mDispatcher->notifyMotion(&upMotionArgs);
2613 // The first window gets nothing and the second gets up
2614 firstWindow->consumeMotionUp();
2615 secondWindow->assertNoEvents();
2616}
2617
Arthur Hungabbb9d82021-09-01 14:52:30 +00002618// This case will create two windows and one mirrored window on the default display and mirror
2619// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2620// the windows info of second display before default display.
2621TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2622 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2623 sp<FakeWindowHandle> firstWindowInPrimary =
2624 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2625 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002626 sp<FakeWindowHandle> secondWindowInPrimary =
2627 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2628 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002629
2630 sp<FakeWindowHandle> mirrorWindowInPrimary =
2631 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2632 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002633
2634 sp<FakeWindowHandle> firstWindowInSecondary =
2635 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2636 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002637
2638 sp<FakeWindowHandle> secondWindowInSecondary =
2639 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2640 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002641
2642 // Update window info, let it find window handle of second display first.
2643 mDispatcher->setInputWindows(
2644 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2645 {ADISPLAY_ID_DEFAULT,
2646 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2647
2648 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2649 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2650 {50, 50}))
2651 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2652
2653 // Window should receive motion event.
2654 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2655
2656 // Transfer touch focus
2657 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2658 secondWindowInPrimary->getToken()));
2659 // The first window gets cancel.
2660 firstWindowInPrimary->consumeMotionCancel();
2661 secondWindowInPrimary->consumeMotionDown();
2662
2663 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2664 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2665 ADISPLAY_ID_DEFAULT, {150, 50}))
2666 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2667 firstWindowInPrimary->assertNoEvents();
2668 secondWindowInPrimary->consumeMotionMove();
2669
2670 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2671 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2672 {150, 50}))
2673 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2674 firstWindowInPrimary->assertNoEvents();
2675 secondWindowInPrimary->consumeMotionUp();
2676}
2677
2678// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2679// 'transferTouch' api.
2680TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2681 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2682 sp<FakeWindowHandle> firstWindowInPrimary =
2683 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2684 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002685 sp<FakeWindowHandle> secondWindowInPrimary =
2686 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2687 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002688
2689 sp<FakeWindowHandle> mirrorWindowInPrimary =
2690 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2691 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002692
2693 sp<FakeWindowHandle> firstWindowInSecondary =
2694 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2695 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002696
2697 sp<FakeWindowHandle> secondWindowInSecondary =
2698 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2699 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002700
2701 // Update window info, let it find window handle of second display first.
2702 mDispatcher->setInputWindows(
2703 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2704 {ADISPLAY_ID_DEFAULT,
2705 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2706
2707 // Touch on second display.
2708 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2709 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2710 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2711
2712 // Window should receive motion event.
2713 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2714
2715 // Transfer touch focus
2716 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2717
2718 // The first window gets cancel.
2719 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2720 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2721
2722 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2723 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2724 SECOND_DISPLAY_ID, {150, 50}))
2725 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2726 firstWindowInPrimary->assertNoEvents();
2727 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2728
2729 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2730 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2731 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2732 firstWindowInPrimary->assertNoEvents();
2733 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2734}
2735
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002736TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002737 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002738 sp<FakeWindowHandle> window =
2739 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2740
Vishnu Nair47074b82020-08-14 11:54:47 -07002741 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002742 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002743 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002744
2745 window->consumeFocusEvent(true);
2746
2747 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2748 mDispatcher->notifyKey(&keyArgs);
2749
2750 // Window should receive key down event.
2751 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2752}
2753
2754TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002755 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002756 sp<FakeWindowHandle> window =
2757 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2758
Arthur Hung72d8dc32020-03-28 00:48:39 +00002759 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002760
2761 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2762 mDispatcher->notifyKey(&keyArgs);
2763 mDispatcher->waitForIdle();
2764
2765 window->assertNoEvents();
2766}
2767
2768// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2769TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002770 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002771 sp<FakeWindowHandle> window =
2772 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2773
Arthur Hung72d8dc32020-03-28 00:48:39 +00002774 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002775
2776 // Send key
2777 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2778 mDispatcher->notifyKey(&keyArgs);
2779 // Send motion
2780 NotifyMotionArgs motionArgs =
2781 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2782 ADISPLAY_ID_DEFAULT);
2783 mDispatcher->notifyMotion(&motionArgs);
2784
2785 // Window should receive only the motion event
2786 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2787 window->assertNoEvents(); // Key event or focus event will not be received
2788}
2789
arthurhungea3f4fc2020-12-21 23:18:53 +08002790TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2791 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2792
arthurhungea3f4fc2020-12-21 23:18:53 +08002793 sp<FakeWindowHandle> firstWindow =
2794 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2795 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08002796
arthurhungea3f4fc2020-12-21 23:18:53 +08002797 sp<FakeWindowHandle> secondWindow =
2798 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2799 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08002800
2801 // Add the windows to the dispatcher
2802 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2803
2804 PointF pointInFirst = {300, 200};
2805 PointF pointInSecond = {300, 600};
2806
2807 // Send down to the first window
2808 NotifyMotionArgs firstDownMotionArgs =
2809 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2810 ADISPLAY_ID_DEFAULT, {pointInFirst});
2811 mDispatcher->notifyMotion(&firstDownMotionArgs);
2812 // Only the first window should get the down event
2813 firstWindow->consumeMotionDown();
2814 secondWindow->assertNoEvents();
2815
2816 // Send down to the second window
2817 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002818 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08002819 {pointInFirst, pointInSecond});
2820 mDispatcher->notifyMotion(&secondDownMotionArgs);
2821 // The first window gets a move and the second a down
2822 firstWindow->consumeMotionMove();
2823 secondWindow->consumeMotionDown();
2824
2825 // Send pointer cancel to the second window
2826 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002827 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08002828 {pointInFirst, pointInSecond});
2829 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2830 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2831 // The first window gets move and the second gets cancel.
2832 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2833 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2834
2835 // Send up event.
2836 NotifyMotionArgs upMotionArgs =
2837 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2838 ADISPLAY_ID_DEFAULT);
2839 mDispatcher->notifyMotion(&upMotionArgs);
2840 // The first window gets up and the second gets nothing.
2841 firstWindow->consumeMotionUp();
2842 secondWindow->assertNoEvents();
2843}
2844
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002845TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2846 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2847
2848 sp<FakeWindowHandle> window =
2849 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2850 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2851 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2852 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2853 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2854
2855 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2856 window->assertNoEvents();
2857 mDispatcher->waitForIdle();
2858}
2859
chaviwd1c23182019-12-20 18:44:56 -08002860class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002861public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002862 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002863 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07002864 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002865 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002866 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002867 }
2868
chaviwd1c23182019-12-20 18:44:56 -08002869 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2870
2871 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2872 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2873 expectedDisplayId, expectedFlags);
2874 }
2875
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002876 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2877
2878 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2879
chaviwd1c23182019-12-20 18:44:56 -08002880 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2881 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2882 expectedDisplayId, expectedFlags);
2883 }
2884
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002885 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2886 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2887 expectedDisplayId, expectedFlags);
2888 }
2889
chaviwd1c23182019-12-20 18:44:56 -08002890 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2891 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2892 expectedDisplayId, expectedFlags);
2893 }
2894
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002895 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2896 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2897 expectedDisplayId, expectedFlags);
2898 }
2899
Arthur Hungfbfa5722021-11-16 02:45:54 +00002900 void consumeMotionPointerDown(int32_t pointerIdx) {
2901 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2902 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2903 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2904 0 /*expectedFlags*/);
2905 }
2906
Evan Rosky84f07f02021-04-16 10:42:42 -07002907 MotionEvent* consumeMotion() {
2908 InputEvent* event = mInputReceiver->consume();
2909 if (!event) {
2910 ADD_FAILURE() << "No event was produced";
2911 return nullptr;
2912 }
2913 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2914 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2915 return nullptr;
2916 }
2917 return static_cast<MotionEvent*>(event);
2918 }
2919
chaviwd1c23182019-12-20 18:44:56 -08002920 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2921
2922private:
2923 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002924};
2925
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002926using InputDispatcherMonitorTest = InputDispatcherTest;
2927
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002928/**
2929 * Two entities that receive touch: A window, and a global monitor.
2930 * The touch goes to the window, and then the window disappears.
2931 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2932 * for the monitor, as well.
2933 * 1. foregroundWindow
2934 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2935 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002936TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002937 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2938 sp<FakeWindowHandle> window =
2939 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2940
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002941 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002942
2943 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2944 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2945 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2946 {100, 200}))
2947 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2948
2949 // Both the foreground window and the global monitor should receive the touch down
2950 window->consumeMotionDown();
2951 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2952
2953 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2954 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2955 ADISPLAY_ID_DEFAULT, {110, 200}))
2956 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2957
2958 window->consumeMotionMove();
2959 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2960
2961 // Now the foreground window goes away
2962 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2963 window->consumeMotionCancel();
2964 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2965
2966 // If more events come in, there will be no more foreground window to send them to. This will
2967 // cause a cancel for the monitor, as well.
2968 ASSERT_EQ(InputEventInjectionResult::FAILED,
2969 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2970 ADISPLAY_ID_DEFAULT, {120, 200}))
2971 << "Injection should fail because the window was removed";
2972 window->assertNoEvents();
2973 // Global monitor now gets the cancel
2974 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2975}
2976
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002977TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002978 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002979 sp<FakeWindowHandle> window =
2980 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002981 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002982
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002983 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002984
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002985 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002986 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002987 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002988 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002989 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002990}
2991
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002992TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
2993 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002994
Chris Yea209fde2020-07-22 13:54:51 -07002995 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002996 sp<FakeWindowHandle> window =
2997 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002998 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002999
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003000 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003001 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003002 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003003 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003004 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003005
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003006 // Pilfer pointers from the monitor.
3007 // This should not do anything and the window should continue to receive events.
3008 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003009
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003010 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003011 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3012 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003013 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003014
3015 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3016 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003017}
3018
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003019TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003020 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3021 sp<FakeWindowHandle> window =
3022 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3023 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3024 window->setWindowOffset(20, 40);
3025 window->setWindowTransform(0, 1, -1, 0);
3026
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003027 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003028
3029 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3030 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3031 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3032 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3033 MotionEvent* event = monitor.consumeMotion();
3034 // Even though window has transform, gesture monitor must not.
3035 ASSERT_EQ(ui::Transform(), event->getTransform());
3036}
3037
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003038TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003039 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003040 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003041
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003042 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003043 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003044 << "Injection should fail if there is a monitor, but no touchable window";
3045 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003046}
3047
chaviw81e2bb92019-12-18 15:03:51 -08003048TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003049 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08003050 sp<FakeWindowHandle> window =
3051 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3052
Arthur Hung72d8dc32020-03-28 00:48:39 +00003053 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003054
3055 NotifyMotionArgs motionArgs =
3056 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3057 ADISPLAY_ID_DEFAULT);
3058
3059 mDispatcher->notifyMotion(&motionArgs);
3060 // Window should receive motion down event.
3061 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3062
3063 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003064 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003065 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3066 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3067 motionArgs.pointerCoords[0].getX() - 10);
3068
3069 mDispatcher->notifyMotion(&motionArgs);
3070 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3071 0 /*expectedFlags*/);
3072}
3073
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003074/**
3075 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3076 * the device default right away. In the test scenario, we check both the default value,
3077 * and the action of enabling / disabling.
3078 */
3079TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003080 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003081 sp<FakeWindowHandle> window =
3082 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003083 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003084
3085 // Set focused application.
3086 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003087 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003088
3089 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003090 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003091 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003092 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3093
3094 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003095 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003096 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003097 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3098
3099 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003100 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3101 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003102 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003103 window->setFocusable(true);
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*/, false /*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*/, false /*inTouchMode*/);
3112
3113 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003114 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3115 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003116 window->consumeTouchModeEvent(true);
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*/, true /*inTouchMode*/);
3121
3122 window->assertNoEvents();
3123}
3124
Gang Wange9087892020-01-07 12:17:14 -05003125TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003126 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003127 sp<FakeWindowHandle> window =
3128 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3129
3130 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003131 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003132
Arthur Hung72d8dc32020-03-28 00:48:39 +00003133 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003134 setFocusedWindow(window);
3135
Gang Wange9087892020-01-07 12:17:14 -05003136 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3137
3138 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3139 mDispatcher->notifyKey(&keyArgs);
3140
3141 InputEvent* event = window->consume();
3142 ASSERT_NE(event, nullptr);
3143
3144 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3145 ASSERT_NE(verified, nullptr);
3146 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3147
3148 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3149 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3150 ASSERT_EQ(keyArgs.source, verified->source);
3151 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3152
3153 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3154
3155 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003156 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003157 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003158 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3159 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3160 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3161 ASSERT_EQ(0, verifiedKey.repeatCount);
3162}
3163
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003164TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003165 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003166 sp<FakeWindowHandle> window =
3167 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3168
3169 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3170
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003171 ui::Transform transform;
3172 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3173
3174 gui::DisplayInfo displayInfo;
3175 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3176 displayInfo.transform = transform;
3177
3178 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003179
3180 NotifyMotionArgs motionArgs =
3181 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3182 ADISPLAY_ID_DEFAULT);
3183 mDispatcher->notifyMotion(&motionArgs);
3184
3185 InputEvent* event = window->consume();
3186 ASSERT_NE(event, nullptr);
3187
3188 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3189 ASSERT_NE(verified, nullptr);
3190 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3191
3192 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3193 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3194 EXPECT_EQ(motionArgs.source, verified->source);
3195 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3196
3197 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3198
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003199 const vec2 rawXY =
3200 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3201 motionArgs.pointerCoords[0].getXYValue());
3202 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3203 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003204 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003205 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003206 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003207 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3208 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3209}
3210
chaviw09c8d2d2020-08-24 15:48:26 -07003211/**
3212 * Ensure that separate calls to sign the same data are generating the same key.
3213 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3214 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3215 * tests.
3216 */
3217TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3218 KeyEvent event = getTestKeyEvent();
3219 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3220
3221 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3222 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3223 ASSERT_EQ(hmac1, hmac2);
3224}
3225
3226/**
3227 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3228 */
3229TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3230 KeyEvent event = getTestKeyEvent();
3231 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3232 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3233
3234 verifiedEvent.deviceId += 1;
3235 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3236
3237 verifiedEvent.source += 1;
3238 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3239
3240 verifiedEvent.eventTimeNanos += 1;
3241 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3242
3243 verifiedEvent.displayId += 1;
3244 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3245
3246 verifiedEvent.action += 1;
3247 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3248
3249 verifiedEvent.downTimeNanos += 1;
3250 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3251
3252 verifiedEvent.flags += 1;
3253 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3254
3255 verifiedEvent.keyCode += 1;
3256 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3257
3258 verifiedEvent.scanCode += 1;
3259 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3260
3261 verifiedEvent.metaState += 1;
3262 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3263
3264 verifiedEvent.repeatCount += 1;
3265 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3266}
3267
Vishnu Nair958da932020-08-21 17:12:37 -07003268TEST_F(InputDispatcherTest, SetFocusedWindow) {
3269 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3270 sp<FakeWindowHandle> windowTop =
3271 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3272 sp<FakeWindowHandle> windowSecond =
3273 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3274 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3275
3276 // Top window is also focusable but is not granted focus.
3277 windowTop->setFocusable(true);
3278 windowSecond->setFocusable(true);
3279 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3280 setFocusedWindow(windowSecond);
3281
3282 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003283 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3284 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003285
3286 // Focused window should receive event.
3287 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3288 windowTop->assertNoEvents();
3289}
3290
3291TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3292 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3293 sp<FakeWindowHandle> window =
3294 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3295 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3296
3297 window->setFocusable(true);
3298 // Release channel for window is no longer valid.
3299 window->releaseChannel();
3300 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3301 setFocusedWindow(window);
3302
3303 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003304 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3305 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003306
3307 // window channel is invalid, so it should not receive any input event.
3308 window->assertNoEvents();
3309}
3310
3311TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3312 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3313 sp<FakeWindowHandle> window =
3314 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003315 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003316 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3317
Vishnu Nair958da932020-08-21 17:12:37 -07003318 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3319 setFocusedWindow(window);
3320
3321 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003322 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3323 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003324
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003325 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003326 window->assertNoEvents();
3327}
3328
3329TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3330 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3331 sp<FakeWindowHandle> windowTop =
3332 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3333 sp<FakeWindowHandle> windowSecond =
3334 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3335 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3336
3337 windowTop->setFocusable(true);
3338 windowSecond->setFocusable(true);
3339 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3340 setFocusedWindow(windowTop);
3341 windowTop->consumeFocusEvent(true);
3342
3343 setFocusedWindow(windowSecond, windowTop);
3344 windowSecond->consumeFocusEvent(true);
3345 windowTop->consumeFocusEvent(false);
3346
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003347 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3348 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003349
3350 // Focused window should receive event.
3351 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3352}
3353
3354TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3355 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3356 sp<FakeWindowHandle> windowTop =
3357 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3358 sp<FakeWindowHandle> windowSecond =
3359 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3360 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3361
3362 windowTop->setFocusable(true);
3363 windowSecond->setFocusable(true);
3364 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3365 setFocusedWindow(windowSecond, windowTop);
3366
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003367 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3368 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003369
3370 // Event should be dropped.
3371 windowTop->assertNoEvents();
3372 windowSecond->assertNoEvents();
3373}
3374
3375TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3376 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3377 sp<FakeWindowHandle> window =
3378 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3379 sp<FakeWindowHandle> previousFocusedWindow =
3380 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3381 ADISPLAY_ID_DEFAULT);
3382 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3383
3384 window->setFocusable(true);
3385 previousFocusedWindow->setFocusable(true);
3386 window->setVisible(false);
3387 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3388 setFocusedWindow(previousFocusedWindow);
3389 previousFocusedWindow->consumeFocusEvent(true);
3390
3391 // Requesting focus on invisible window takes focus from currently focused window.
3392 setFocusedWindow(window);
3393 previousFocusedWindow->consumeFocusEvent(false);
3394
3395 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003396 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003397 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003398 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003399
3400 // Window does not get focus event or key down.
3401 window->assertNoEvents();
3402
3403 // Window becomes visible.
3404 window->setVisible(true);
3405 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3406
3407 // Window receives focus event.
3408 window->consumeFocusEvent(true);
3409 // Focused window receives key down.
3410 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3411}
3412
Vishnu Nair599f1412021-06-21 10:39:58 -07003413TEST_F(InputDispatcherTest, DisplayRemoved) {
3414 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3415 sp<FakeWindowHandle> window =
3416 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3417 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3418
3419 // window is granted focus.
3420 window->setFocusable(true);
3421 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3422 setFocusedWindow(window);
3423 window->consumeFocusEvent(true);
3424
3425 // When a display is removed window loses focus.
3426 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3427 window->consumeFocusEvent(false);
3428}
3429
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003430/**
3431 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3432 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3433 * of the 'slipperyEnterWindow'.
3434 *
3435 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3436 * a way so that the touched location is no longer covered by the top window.
3437 *
3438 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3439 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3440 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3441 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3442 * with ACTION_DOWN).
3443 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3444 * window moved itself away from the touched location and had Flag::SLIPPERY.
3445 *
3446 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3447 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3448 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3449 *
3450 * In this test, we ensure that the event received by the bottom window has
3451 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3452 */
3453TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3454 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3455 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3456
3457 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3458 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3459
3460 sp<FakeWindowHandle> slipperyExitWindow =
3461 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003462 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003463 // Make sure this one overlaps the bottom window
3464 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3465 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3466 // one. Windows with the same owner are not considered to be occluding each other.
3467 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3468
3469 sp<FakeWindowHandle> slipperyEnterWindow =
3470 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3471 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3472
3473 mDispatcher->setInputWindows(
3474 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3475
3476 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3477 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3478 ADISPLAY_ID_DEFAULT, {{50, 50}});
3479 mDispatcher->notifyMotion(&args);
3480 slipperyExitWindow->consumeMotionDown();
3481 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3482 mDispatcher->setInputWindows(
3483 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3484
3485 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3486 ADISPLAY_ID_DEFAULT, {{51, 51}});
3487 mDispatcher->notifyMotion(&args);
3488
3489 slipperyExitWindow->consumeMotionCancel();
3490
3491 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3492 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3493}
3494
Garfield Tan1c7bc862020-01-28 13:24:04 -08003495class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3496protected:
3497 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3498 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3499
Chris Yea209fde2020-07-22 13:54:51 -07003500 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003501 sp<FakeWindowHandle> mWindow;
3502
3503 virtual void SetUp() override {
3504 mFakePolicy = new FakeInputDispatcherPolicy();
3505 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003506 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003507 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3508 ASSERT_EQ(OK, mDispatcher->start());
3509
3510 setUpWindow();
3511 }
3512
3513 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003514 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003515 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3516
Vishnu Nair47074b82020-08-14 11:54:47 -07003517 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003518 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003519 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003520 mWindow->consumeFocusEvent(true);
3521 }
3522
Chris Ye2ad95392020-09-01 13:44:44 -07003523 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003524 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003525 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003526 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3527 mDispatcher->notifyKey(&keyArgs);
3528
3529 // Window should receive key down event.
3530 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3531 }
3532
3533 void expectKeyRepeatOnce(int32_t repeatCount) {
3534 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3535 InputEvent* repeatEvent = mWindow->consume();
3536 ASSERT_NE(nullptr, repeatEvent);
3537
3538 uint32_t eventType = repeatEvent->getType();
3539 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3540
3541 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3542 uint32_t eventAction = repeatKeyEvent->getAction();
3543 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3544 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3545 }
3546
Chris Ye2ad95392020-09-01 13:44:44 -07003547 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003548 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003549 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003550 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3551 mDispatcher->notifyKey(&keyArgs);
3552
3553 // Window should receive key down event.
3554 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3555 0 /*expectedFlags*/);
3556 }
3557};
3558
3559TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003560 sendAndConsumeKeyDown(1 /* deviceId */);
3561 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3562 expectKeyRepeatOnce(repeatCount);
3563 }
3564}
3565
3566TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3567 sendAndConsumeKeyDown(1 /* deviceId */);
3568 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3569 expectKeyRepeatOnce(repeatCount);
3570 }
3571 sendAndConsumeKeyDown(2 /* deviceId */);
3572 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003573 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3574 expectKeyRepeatOnce(repeatCount);
3575 }
3576}
3577
3578TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003579 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003580 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003581 sendAndConsumeKeyUp(1 /* deviceId */);
3582 mWindow->assertNoEvents();
3583}
3584
3585TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3586 sendAndConsumeKeyDown(1 /* deviceId */);
3587 expectKeyRepeatOnce(1 /*repeatCount*/);
3588 sendAndConsumeKeyDown(2 /* deviceId */);
3589 expectKeyRepeatOnce(1 /*repeatCount*/);
3590 // Stale key up from device 1.
3591 sendAndConsumeKeyUp(1 /* deviceId */);
3592 // Device 2 is still down, keep repeating
3593 expectKeyRepeatOnce(2 /*repeatCount*/);
3594 expectKeyRepeatOnce(3 /*repeatCount*/);
3595 // Device 2 key up
3596 sendAndConsumeKeyUp(2 /* deviceId */);
3597 mWindow->assertNoEvents();
3598}
3599
3600TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3601 sendAndConsumeKeyDown(1 /* deviceId */);
3602 expectKeyRepeatOnce(1 /*repeatCount*/);
3603 sendAndConsumeKeyDown(2 /* deviceId */);
3604 expectKeyRepeatOnce(1 /*repeatCount*/);
3605 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3606 sendAndConsumeKeyUp(2 /* deviceId */);
3607 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003608 mWindow->assertNoEvents();
3609}
3610
liushenxiang42232912021-05-21 20:24:09 +08003611TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3612 sendAndConsumeKeyDown(DEVICE_ID);
3613 expectKeyRepeatOnce(1 /*repeatCount*/);
3614 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3615 mDispatcher->notifyDeviceReset(&args);
3616 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3617 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3618 mWindow->assertNoEvents();
3619}
3620
Garfield Tan1c7bc862020-01-28 13:24:04 -08003621TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003622 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003623 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3624 InputEvent* repeatEvent = mWindow->consume();
3625 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3626 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3627 IdGenerator::getSource(repeatEvent->getId()));
3628 }
3629}
3630
3631TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003632 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003633
3634 std::unordered_set<int32_t> idSet;
3635 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3636 InputEvent* repeatEvent = mWindow->consume();
3637 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3638 int32_t id = repeatEvent->getId();
3639 EXPECT_EQ(idSet.end(), idSet.find(id));
3640 idSet.insert(id);
3641 }
3642}
3643
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003644/* Test InputDispatcher for MultiDisplay */
3645class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3646public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003647 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003648 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003649
Chris Yea209fde2020-07-22 13:54:51 -07003650 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003651 windowInPrimary =
3652 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003653
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003654 // Set focus window for primary display, but focused display would be second one.
3655 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003656 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003657 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003658 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003659 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003660
Chris Yea209fde2020-07-22 13:54:51 -07003661 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003662 windowInSecondary =
3663 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003664 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003665 // Set focus display to second one.
3666 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3667 // Set focus window for second display.
3668 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003669 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003670 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003671 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003672 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003673 }
3674
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003675 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003676 InputDispatcherTest::TearDown();
3677
Chris Yea209fde2020-07-22 13:54:51 -07003678 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003679 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003680 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003681 windowInSecondary.clear();
3682 }
3683
3684protected:
Chris Yea209fde2020-07-22 13:54:51 -07003685 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003686 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003687 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003688 sp<FakeWindowHandle> windowInSecondary;
3689};
3690
3691TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3692 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003693 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3694 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3695 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003696 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003697 windowInSecondary->assertNoEvents();
3698
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003699 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003700 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3701 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3702 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003703 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003704 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003705}
3706
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003707TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003708 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003709 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3710 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003711 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003712 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003713 windowInSecondary->assertNoEvents();
3714
3715 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003716 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003717 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003718 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003719 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003720
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003721 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003722 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003723
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003724 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003725 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3726 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003727
3728 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003729 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003730 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003731 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003732 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003733 windowInSecondary->assertNoEvents();
3734}
3735
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003736// Test per-display input monitors for motion event.
3737TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003738 FakeMonitorReceiver monitorInPrimary =
3739 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3740 FakeMonitorReceiver monitorInSecondary =
3741 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003742
3743 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003744 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3745 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3746 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003747 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003748 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003749 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003750 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003751
3752 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003753 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3754 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3755 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003756 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003757 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003758 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003759 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003760
3761 // Test inject a non-pointer motion event.
3762 // If specific a display, it will dispatch to the focused window of particular display,
3763 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003764 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3765 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3766 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003767 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003768 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003769 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003770 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003771}
3772
3773// Test per-display input monitors for key event.
3774TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003775 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003776 FakeMonitorReceiver monitorInPrimary =
3777 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3778 FakeMonitorReceiver monitorInSecondary =
3779 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003780
3781 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003782 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3783 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003784 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003785 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003786 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003787 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003788}
3789
Vishnu Nair958da932020-08-21 17:12:37 -07003790TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3791 sp<FakeWindowHandle> secondWindowInPrimary =
3792 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3793 secondWindowInPrimary->setFocusable(true);
3794 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3795 setFocusedWindow(secondWindowInPrimary);
3796 windowInPrimary->consumeFocusEvent(false);
3797 secondWindowInPrimary->consumeFocusEvent(true);
3798
3799 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003800 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3801 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003802 windowInPrimary->assertNoEvents();
3803 windowInSecondary->assertNoEvents();
3804 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3805}
3806
Arthur Hungdfd528e2021-12-08 13:23:04 +00003807TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3808 FakeMonitorReceiver monitorInPrimary =
3809 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3810 FakeMonitorReceiver monitorInSecondary =
3811 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3812
3813 // Test touch down on primary display.
3814 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3815 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3816 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3817 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3818 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3819
3820 // Test touch down on second display.
3821 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3822 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3823 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3824 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3825 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3826
3827 // Trigger cancel touch.
3828 mDispatcher->cancelCurrentTouch();
3829 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3830 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3831 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3832 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3833
3834 // Test inject a move motion event, no window/monitor should receive the event.
3835 ASSERT_EQ(InputEventInjectionResult::FAILED,
3836 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3837 ADISPLAY_ID_DEFAULT, {110, 200}))
3838 << "Inject motion event should return InputEventInjectionResult::FAILED";
3839 windowInPrimary->assertNoEvents();
3840 monitorInPrimary.assertNoEvents();
3841
3842 ASSERT_EQ(InputEventInjectionResult::FAILED,
3843 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3844 SECOND_DISPLAY_ID, {110, 200}))
3845 << "Inject motion event should return InputEventInjectionResult::FAILED";
3846 windowInSecondary->assertNoEvents();
3847 monitorInSecondary.assertNoEvents();
3848}
3849
Jackal Guof9696682018-10-05 12:23:23 +08003850class InputFilterTest : public InputDispatcherTest {
3851protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003852 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3853 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003854 NotifyMotionArgs motionArgs;
3855
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003856 motionArgs =
3857 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003858 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003859 motionArgs =
3860 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003861 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003862 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003863 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003864 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3865 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003866 } else {
3867 mFakePolicy->assertFilterInputEventWasNotCalled();
3868 }
3869 }
3870
3871 void testNotifyKey(bool expectToBeFiltered) {
3872 NotifyKeyArgs keyArgs;
3873
3874 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3875 mDispatcher->notifyKey(&keyArgs);
3876 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3877 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003878 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003879
3880 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003881 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003882 } else {
3883 mFakePolicy->assertFilterInputEventWasNotCalled();
3884 }
3885 }
3886};
3887
3888// Test InputFilter for MotionEvent
3889TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3890 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3891 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3892 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3893
3894 // Enable InputFilter
3895 mDispatcher->setInputFilterEnabled(true);
3896 // Test touch on both primary and second display, and check if both events are filtered.
3897 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3898 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3899
3900 // Disable InputFilter
3901 mDispatcher->setInputFilterEnabled(false);
3902 // Test touch on both primary and second display, and check if both events aren't filtered.
3903 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3904 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3905}
3906
3907// Test InputFilter for KeyEvent
3908TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3909 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3910 testNotifyKey(/*expectToBeFiltered*/ false);
3911
3912 // Enable InputFilter
3913 mDispatcher->setInputFilterEnabled(true);
3914 // Send a key event, and check if it is filtered.
3915 testNotifyKey(/*expectToBeFiltered*/ true);
3916
3917 // Disable InputFilter
3918 mDispatcher->setInputFilterEnabled(false);
3919 // Send a key event, and check if it isn't filtered.
3920 testNotifyKey(/*expectToBeFiltered*/ false);
3921}
3922
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003923// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3924// logical display coordinate space.
3925TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3926 ui::Transform firstDisplayTransform;
3927 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3928 ui::Transform secondDisplayTransform;
3929 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3930
3931 std::vector<gui::DisplayInfo> displayInfos(2);
3932 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3933 displayInfos[0].transform = firstDisplayTransform;
3934 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3935 displayInfos[1].transform = secondDisplayTransform;
3936
3937 mDispatcher->onWindowInfosChanged({}, displayInfos);
3938
3939 // Enable InputFilter
3940 mDispatcher->setInputFilterEnabled(true);
3941
3942 // Ensure the correct transforms are used for the displays.
3943 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3944 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3945}
3946
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003947class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3948protected:
3949 virtual void SetUp() override {
3950 InputDispatcherTest::SetUp();
3951
3952 /**
3953 * We don't need to enable input filter to test the injected event policy, but we enabled it
3954 * here to make the tests more realistic, since this policy only matters when inputfilter is
3955 * on.
3956 */
3957 mDispatcher->setInputFilterEnabled(true);
3958
3959 std::shared_ptr<InputApplicationHandle> application =
3960 std::make_shared<FakeApplicationHandle>();
3961 mWindow =
3962 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3963
3964 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3965 mWindow->setFocusable(true);
3966 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3967 setFocusedWindow(mWindow);
3968 mWindow->consumeFocusEvent(true);
3969 }
3970
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003971 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3972 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003973 KeyEvent event;
3974
3975 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3976 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3977 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3978 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3979 const int32_t additionalPolicyFlags =
3980 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3981 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3982 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3983 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3984 policyFlags | additionalPolicyFlags));
3985
3986 InputEvent* received = mWindow->consume();
3987 ASSERT_NE(nullptr, received);
3988 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003989 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3990 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3991 ASSERT_EQ(flags, keyEvent.getFlags());
3992 }
3993
3994 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3995 int32_t flags) {
3996 MotionEvent event;
3997 PointerProperties pointerProperties[1];
3998 PointerCoords pointerCoords[1];
3999 pointerProperties[0].clear();
4000 pointerProperties[0].id = 0;
4001 pointerCoords[0].clear();
4002 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4003 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4004
4005 ui::Transform identityTransform;
4006 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4007 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4008 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4009 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4010 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004011 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004012 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004013 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4014
4015 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4016 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4017 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
4018 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4019 policyFlags | additionalPolicyFlags));
4020
4021 InputEvent* received = mWindow->consume();
4022 ASSERT_NE(nullptr, received);
4023 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4024 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4025 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4026 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004027 }
4028
4029private:
4030 sp<FakeWindowHandle> mWindow;
4031};
4032
4033TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004034 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4035 // filter. Without it, the event will no different from a regularly injected event, and the
4036 // injected device id will be overwritten.
4037 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4038 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004039}
4040
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004041TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004042 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004043 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4044 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4045}
4046
4047TEST_F(InputFilterInjectionPolicyTest,
4048 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4049 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4050 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4051 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004052}
4053
4054TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4055 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004056 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004057}
4058
chaviwfd6d3512019-03-25 13:23:49 -07004059class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004060 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004061 InputDispatcherTest::SetUp();
4062
Chris Yea209fde2020-07-22 13:54:51 -07004063 std::shared_ptr<FakeApplicationHandle> application =
4064 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004065 mUnfocusedWindow =
4066 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004067 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004068
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004069 mFocusedWindow =
4070 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4071 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004072
4073 // Set focused application.
4074 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004075 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004076
4077 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004078 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004079 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004080 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004081 }
4082
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004083 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004084 InputDispatcherTest::TearDown();
4085
4086 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004087 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004088 }
4089
4090protected:
4091 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004092 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004093 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004094};
4095
4096// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4097// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4098// the onPointerDownOutsideFocus callback.
4099TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004100 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004101 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4102 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004103 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004104 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004105
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004106 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004107 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4108}
4109
4110// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4111// DOWN on the window that doesn't have focus. Ensure no window received the
4112// onPointerDownOutsideFocus callback.
4113TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004114 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004115 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004116 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004117 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004118
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004119 ASSERT_TRUE(mDispatcher->waitForIdle());
4120 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004121}
4122
4123// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4124// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4125TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004126 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4127 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004128 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004129 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004130
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004131 ASSERT_TRUE(mDispatcher->waitForIdle());
4132 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004133}
4134
4135// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4136// DOWN on the window that already has focus. Ensure no window received the
4137// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004138TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004139 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004140 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004141 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004142 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004143 mFocusedWindow->consumeMotionDown();
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
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004149// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4150// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4151TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4152 const MotionEvent event =
4153 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4154 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4155 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4156 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4157 .build();
4158 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4159 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4160 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4161
4162 ASSERT_TRUE(mDispatcher->waitForIdle());
4163 mFakePolicy->assertOnPointerDownWasNotCalled();
4164 // Ensure that the unfocused window did not receive any FOCUS events.
4165 mUnfocusedWindow->assertNoEvents();
4166}
4167
chaviwaf87b3e2019-10-01 16:59:28 -07004168// These tests ensures we can send touch events to a single client when there are multiple input
4169// windows that point to the same client token.
4170class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4171 virtual void SetUp() override {
4172 InputDispatcherTest::SetUp();
4173
Chris Yea209fde2020-07-22 13:54:51 -07004174 std::shared_ptr<FakeApplicationHandle> application =
4175 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004176 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4177 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004178 mWindow1->setFrame(Rect(0, 0, 100, 100));
4179
4180 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4181 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004182 mWindow2->setFrame(Rect(100, 100, 200, 200));
4183
Arthur Hung72d8dc32020-03-28 00:48:39 +00004184 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004185 }
4186
4187protected:
4188 sp<FakeWindowHandle> mWindow1;
4189 sp<FakeWindowHandle> mWindow2;
4190
4191 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004192 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004193 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4194 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004195 }
4196
4197 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4198 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004199 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004200 InputEvent* event = window->consume();
4201
4202 ASSERT_NE(nullptr, event) << name.c_str()
4203 << ": consumer should have returned non-NULL event.";
4204
4205 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4206 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4207 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4208
4209 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004210 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004211
4212 for (size_t i = 0; i < points.size(); i++) {
4213 float expectedX = points[i].x;
4214 float expectedY = points[i].y;
4215
4216 EXPECT_EQ(expectedX, motionEvent.getX(i))
4217 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4218 << ", got " << motionEvent.getX(i);
4219 EXPECT_EQ(expectedY, motionEvent.getY(i))
4220 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4221 << ", got " << motionEvent.getY(i);
4222 }
4223 }
chaviw9eaa22c2020-07-01 16:21:27 -07004224
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004225 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004226 std::vector<PointF> expectedPoints) {
4227 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4228 ADISPLAY_ID_DEFAULT, touchedPoints);
4229 mDispatcher->notifyMotion(&motionArgs);
4230
4231 // Always consume from window1 since it's the window that has the InputReceiver
4232 consumeMotionEvent(mWindow1, action, expectedPoints);
4233 }
chaviwaf87b3e2019-10-01 16:59:28 -07004234};
4235
4236TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4237 // Touch Window 1
4238 PointF touchedPoint = {10, 10};
4239 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004240 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004241
4242 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004243 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004244
4245 // Touch Window 2
4246 touchedPoint = {150, 150};
4247 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004248 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004249}
4250
chaviw9eaa22c2020-07-01 16:21:27 -07004251TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4252 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004253 mWindow2->setWindowScale(0.5f, 0.5f);
4254
4255 // Touch Window 1
4256 PointF touchedPoint = {10, 10};
4257 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004258 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004259 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004260 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004261
4262 // Touch Window 2
4263 touchedPoint = {150, 150};
4264 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004265 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4266 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004267
chaviw9eaa22c2020-07-01 16:21:27 -07004268 // Update the transform so rotation is set
4269 mWindow2->setWindowTransform(0, -1, 1, 0);
4270 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4271 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004272}
4273
chaviw9eaa22c2020-07-01 16:21:27 -07004274TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004275 mWindow2->setWindowScale(0.5f, 0.5f);
4276
4277 // Touch Window 1
4278 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4279 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004280 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004281
4282 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004283 touchedPoints.push_back(PointF{150, 150});
4284 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004285 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004286
chaviw9eaa22c2020-07-01 16:21:27 -07004287 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004288 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004289 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004290
chaviw9eaa22c2020-07-01 16:21:27 -07004291 // Update the transform so rotation is set for Window 2
4292 mWindow2->setWindowTransform(0, -1, 1, 0);
4293 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004294 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004295}
4296
chaviw9eaa22c2020-07-01 16:21:27 -07004297TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004298 mWindow2->setWindowScale(0.5f, 0.5f);
4299
4300 // Touch Window 1
4301 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4302 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004303 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004304
4305 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004306 touchedPoints.push_back(PointF{150, 150});
4307 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004308
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004309 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004310
4311 // Move both windows
4312 touchedPoints = {{20, 20}, {175, 175}};
4313 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4314 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4315
chaviw9eaa22c2020-07-01 16:21:27 -07004316 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004317
chaviw9eaa22c2020-07-01 16:21:27 -07004318 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004319 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004320 expectedPoints.pop_back();
4321
4322 // Touch Window 2
4323 mWindow2->setWindowTransform(0, -1, 1, 0);
4324 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004325 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004326
4327 // Move both windows
4328 touchedPoints = {{20, 20}, {175, 175}};
4329 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4330 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4331
4332 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004333}
4334
4335TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4336 mWindow1->setWindowScale(0.5f, 0.5f);
4337
4338 // Touch Window 1
4339 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4340 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004341 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004342
4343 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004344 touchedPoints.push_back(PointF{150, 150});
4345 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004346
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004347 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004348
4349 // Move both windows
4350 touchedPoints = {{20, 20}, {175, 175}};
4351 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4352 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4353
chaviw9eaa22c2020-07-01 16:21:27 -07004354 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004355}
4356
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004357class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4358 virtual void SetUp() override {
4359 InputDispatcherTest::SetUp();
4360
Chris Yea209fde2020-07-22 13:54:51 -07004361 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004362 mApplication->setDispatchingTimeout(20ms);
4363 mWindow =
4364 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4365 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004366 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004367 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004368
4369 // Set focused application.
4370 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4371
4372 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004373 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004374 mWindow->consumeFocusEvent(true);
4375 }
4376
4377 virtual void TearDown() override {
4378 InputDispatcherTest::TearDown();
4379 mWindow.clear();
4380 }
4381
4382protected:
Chris Yea209fde2020-07-22 13:54:51 -07004383 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004384 sp<FakeWindowHandle> mWindow;
4385 static constexpr PointF WINDOW_LOCATION = {20, 20};
4386
4387 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004388 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004389 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4390 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004391 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004392 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4393 WINDOW_LOCATION));
4394 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004395
4396 sp<FakeWindowHandle> addSpyWindow() {
4397 sp<FakeWindowHandle> spy =
4398 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4399 spy->setTrustedOverlay(true);
4400 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004401 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004402 spy->setDispatchingTimeout(30ms);
4403 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4404 return spy;
4405 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004406};
4407
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004408// Send a tap and respond, which should not cause an ANR.
4409TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4410 tapOnWindow();
4411 mWindow->consumeMotionDown();
4412 mWindow->consumeMotionUp();
4413 ASSERT_TRUE(mDispatcher->waitForIdle());
4414 mFakePolicy->assertNotifyAnrWasNotCalled();
4415}
4416
4417// Send a regular key and respond, which should not cause an ANR.
4418TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004419 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004420 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4421 ASSERT_TRUE(mDispatcher->waitForIdle());
4422 mFakePolicy->assertNotifyAnrWasNotCalled();
4423}
4424
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004425TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4426 mWindow->setFocusable(false);
4427 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4428 mWindow->consumeFocusEvent(false);
4429
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004430 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004431 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004432 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4433 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004434 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004435 // Key will not go to window because we have no focused window.
4436 // The 'no focused window' ANR timer should start instead.
4437
4438 // Now, the focused application goes away.
4439 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4440 // The key should get dropped and there should be no ANR.
4441
4442 ASSERT_TRUE(mDispatcher->waitForIdle());
4443 mFakePolicy->assertNotifyAnrWasNotCalled();
4444}
4445
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004446// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004447// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4448// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004449TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004450 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004451 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4452 WINDOW_LOCATION));
4453
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004454 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4455 ASSERT_TRUE(sequenceNum);
4456 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004457 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004458
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004459 mWindow->finishEvent(*sequenceNum);
4460 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4461 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004462 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004463 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004464}
4465
4466// Send a key to the app and have the app not respond right away.
4467TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4468 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004469 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004470 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4471 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004472 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004473 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004474 ASSERT_TRUE(mDispatcher->waitForIdle());
4475}
4476
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004477// We have a focused application, but no focused window
4478TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004479 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004480 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4481 mWindow->consumeFocusEvent(false);
4482
4483 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004484 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004485 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4486 WINDOW_LOCATION));
4487 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4488 mDispatcher->waitForIdle();
4489 mFakePolicy->assertNotifyAnrWasNotCalled();
4490
4491 // Once a focused event arrives, we get an ANR for this application
4492 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4493 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004494 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004495 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004496 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004497 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004498 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004499 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004500 ASSERT_TRUE(mDispatcher->waitForIdle());
4501}
4502
4503// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004504// Make sure that we don't notify policy twice about the same ANR.
4505TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004506 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004507 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4508 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004509
4510 // Once a focused event arrives, we get an ANR for this application
4511 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4512 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004513 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004514 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004515 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004516 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004517 const std::chrono::duration appTimeout =
4518 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004519 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004520
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004521 std::this_thread::sleep_for(appTimeout);
4522 // ANR should not be raised again. It is up to policy to do that if it desires.
4523 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004524
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004525 // If we now get a focused window, the ANR should stop, but the policy handles that via
4526 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004527 ASSERT_TRUE(mDispatcher->waitForIdle());
4528}
4529
4530// We have a focused application, but no focused window
4531TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004532 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004533 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4534 mWindow->consumeFocusEvent(false);
4535
4536 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004537 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004538 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004539 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4540 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004541
4542 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004543 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004544
4545 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004546 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004547 ASSERT_TRUE(mDispatcher->waitForIdle());
4548 mWindow->assertNoEvents();
4549}
4550
4551/**
4552 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4553 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4554 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4555 * the ANR mechanism should still work.
4556 *
4557 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4558 * DOWN event, while not responding on the second one.
4559 */
4560TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4561 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4562 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4563 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4564 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4565 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004566 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004567
4568 // Now send ACTION_UP, with identical timestamp
4569 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4570 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4571 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4572 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004573 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004574
4575 // We have now sent down and up. Let's consume first event and then ANR on the second.
4576 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4577 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004578 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004579}
4580
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004581// A spy window can receive an ANR
4582TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4583 sp<FakeWindowHandle> spy = addSpyWindow();
4584
4585 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4586 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4587 WINDOW_LOCATION));
4588 mWindow->consumeMotionDown();
4589
4590 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4591 ASSERT_TRUE(sequenceNum);
4592 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004593 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004594
4595 spy->finishEvent(*sequenceNum);
4596 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4597 0 /*flags*/);
4598 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004599 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004600}
4601
4602// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004603// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004604TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4605 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004606
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004607 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4608 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004609 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004611
4612 // Stuck on the ACTION_UP
4613 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004614 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004615
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004616 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004617 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004618 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4619 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004620
4621 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4622 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004623 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004624 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004625 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004626}
4627
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004628// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004629// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004630TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4631 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004632
4633 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004634 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4635 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004636
4637 mWindow->consumeMotionDown();
4638 // Stuck on the ACTION_UP
4639 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004640 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004641
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004642 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004643 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004644 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4645 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004646
4647 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4648 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004649 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004650 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004651 spy->assertNoEvents();
4652}
4653
4654TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4655 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4656
4657 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4658
4659 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4660 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4661 WINDOW_LOCATION));
4662
4663 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4664 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4665 ASSERT_TRUE(consumeSeq);
4666
Prabir Pradhanedd96402022-02-15 01:46:16 -08004667 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004668
4669 monitor.finishEvent(*consumeSeq);
4670 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4671
4672 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004673 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004674}
4675
4676// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4677// process events, you don't get an anr. When the window later becomes unresponsive again, you
4678// get an ANR again.
4679// 1. tap -> block on ACTION_UP -> receive ANR
4680// 2. consume all pending events (= queue becomes healthy again)
4681// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4682TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4683 tapOnWindow();
4684
4685 mWindow->consumeMotionDown();
4686 // Block on ACTION_UP
4687 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004688 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004689 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4690 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004691 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004692 mWindow->assertNoEvents();
4693
4694 tapOnWindow();
4695 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004696 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004697 mWindow->consumeMotionUp();
4698
4699 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004700 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004701 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004702 mWindow->assertNoEvents();
4703}
4704
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004705// If a connection remains unresponsive for a while, make sure policy is only notified once about
4706// it.
4707TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004708 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004709 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4710 WINDOW_LOCATION));
4711
4712 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004713 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004714 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004715 // 'notifyConnectionUnresponsive' should only be called once per connection
4716 mFakePolicy->assertNotifyAnrWasNotCalled();
4717 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004718 mWindow->consumeMotionDown();
4719 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4720 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4721 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004722 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004723 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004724 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004725}
4726
4727/**
4728 * If a window is processing a motion event, and then a key event comes in, the key event should
4729 * not to to the focused window until the motion is processed.
4730 *
4731 * Warning!!!
4732 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4733 * and the injection timeout that we specify when injecting the key.
4734 * We must have the injection timeout (10ms) be smaller than
4735 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4736 *
4737 * If that value changes, this test should also change.
4738 */
4739TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4740 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4741 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4742
4743 tapOnWindow();
4744 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4745 ASSERT_TRUE(downSequenceNum);
4746 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4747 ASSERT_TRUE(upSequenceNum);
4748 // Don't finish the events yet, and send a key
4749 // Injection will "succeed" because we will eventually give up and send the key to the focused
4750 // window even if motions are still being processed. But because the injection timeout is short,
4751 // we will receive INJECTION_TIMED_OUT as the result.
4752
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004753 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004754 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004755 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4756 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004757 // Key will not be sent to the window, yet, because the window is still processing events
4758 // and the key remains pending, waiting for the touch events to be processed
4759 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4760 ASSERT_FALSE(keySequenceNum);
4761
4762 std::this_thread::sleep_for(500ms);
4763 // if we wait long enough though, dispatcher will give up, and still send the key
4764 // to the focused window, even though we have not yet finished the motion event
4765 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4766 mWindow->finishEvent(*downSequenceNum);
4767 mWindow->finishEvent(*upSequenceNum);
4768}
4769
4770/**
4771 * If a window is processing a motion event, and then a key event comes in, the key event should
4772 * not go to the focused window until the motion is processed.
4773 * If then a new motion comes in, then the pending key event should be going to the currently
4774 * focused window right away.
4775 */
4776TEST_F(InputDispatcherSingleWindowAnr,
4777 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4778 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4779 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4780
4781 tapOnWindow();
4782 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4783 ASSERT_TRUE(downSequenceNum);
4784 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4785 ASSERT_TRUE(upSequenceNum);
4786 // Don't finish the events yet, and send a key
4787 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004788 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004789 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004790 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004791 // At this point, key is still pending, and should not be sent to the application yet.
4792 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4793 ASSERT_FALSE(keySequenceNum);
4794
4795 // Now tap down again. It should cause the pending key to go to the focused window right away.
4796 tapOnWindow();
4797 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4798 // the other events yet. We can finish events in any order.
4799 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4800 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4801 mWindow->consumeMotionDown();
4802 mWindow->consumeMotionUp();
4803 mWindow->assertNoEvents();
4804}
4805
4806class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4807 virtual void SetUp() override {
4808 InputDispatcherTest::SetUp();
4809
Chris Yea209fde2020-07-22 13:54:51 -07004810 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004811 mApplication->setDispatchingTimeout(10ms);
4812 mUnfocusedWindow =
4813 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4814 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004815 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004816 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004817
4818 mFocusedWindow =
4819 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004820 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004821 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004822
4823 // Set focused application.
4824 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004825 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004826
4827 // Expect one focus window exist in display.
4828 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004829 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004830 mFocusedWindow->consumeFocusEvent(true);
4831 }
4832
4833 virtual void TearDown() override {
4834 InputDispatcherTest::TearDown();
4835
4836 mUnfocusedWindow.clear();
4837 mFocusedWindow.clear();
4838 }
4839
4840protected:
Chris Yea209fde2020-07-22 13:54:51 -07004841 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004842 sp<FakeWindowHandle> mUnfocusedWindow;
4843 sp<FakeWindowHandle> mFocusedWindow;
4844 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4845 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4846 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4847
4848 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4849
4850 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4851
4852private:
4853 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004854 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004855 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4856 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004857 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004858 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4859 location));
4860 }
4861};
4862
4863// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4864// should be ANR'd first.
4865TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004866 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004867 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4868 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004869 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004870 mFocusedWindow->consumeMotionDown();
4871 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4872 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4873 // We consumed all events, so no ANR
4874 ASSERT_TRUE(mDispatcher->waitForIdle());
4875 mFakePolicy->assertNotifyAnrWasNotCalled();
4876
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004877 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004878 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4879 FOCUSED_WINDOW_LOCATION));
4880 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4881 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004882
4883 const std::chrono::duration timeout =
4884 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004885 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004886 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4887 // sequence to make it consistent
4888 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004889 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004890 mFocusedWindow->consumeMotionDown();
4891 // This cancel is generated because the connection was unresponsive
4892 mFocusedWindow->consumeMotionCancel();
4893 mFocusedWindow->assertNoEvents();
4894 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004895 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004896 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
4897 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004898 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004899}
4900
4901// If we have 2 windows with identical timeouts that are both unresponsive,
4902// it doesn't matter which order they should have ANR.
4903// But we should receive ANR for both.
4904TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4905 // Set the timeout for unfocused window to match the focused window
4906 mUnfocusedWindow->setDispatchingTimeout(10ms);
4907 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4908
4909 tapOnFocusedWindow();
4910 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08004911 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
4912 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
4913 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004914
4915 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004916 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4917 mFocusedWindow->getToken() == anrConnectionToken2);
4918 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4919 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004920
4921 ASSERT_TRUE(mDispatcher->waitForIdle());
4922 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004923
4924 mFocusedWindow->consumeMotionDown();
4925 mFocusedWindow->consumeMotionUp();
4926 mUnfocusedWindow->consumeMotionOutside();
4927
Prabir Pradhanedd96402022-02-15 01:46:16 -08004928 sp<IBinder> responsiveToken1, responsiveToken2;
4929 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
4930 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004931
4932 // Both applications should be marked as responsive, in any order
4933 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4934 mFocusedWindow->getToken() == responsiveToken2);
4935 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4936 mUnfocusedWindow->getToken() == responsiveToken2);
4937 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004938}
4939
4940// If a window is already not responding, the second tap on the same window should be ignored.
4941// We should also log an error to account for the dropped event (not tested here).
4942// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4943TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4944 tapOnFocusedWindow();
4945 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4946 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4947 // Receive the events, but don't respond
4948 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4949 ASSERT_TRUE(downEventSequenceNum);
4950 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4951 ASSERT_TRUE(upEventSequenceNum);
4952 const std::chrono::duration timeout =
4953 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004954 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004955
4956 // Tap once again
4957 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004958 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004959 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4960 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004961 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004962 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4963 FOCUSED_WINDOW_LOCATION));
4964 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4965 // valid touch target
4966 mUnfocusedWindow->assertNoEvents();
4967
4968 // Consume the first tap
4969 mFocusedWindow->finishEvent(*downEventSequenceNum);
4970 mFocusedWindow->finishEvent(*upEventSequenceNum);
4971 ASSERT_TRUE(mDispatcher->waitForIdle());
4972 // The second tap did not go to the focused window
4973 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004974 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08004975 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
4976 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004977 mFakePolicy->assertNotifyAnrWasNotCalled();
4978}
4979
4980// If you tap outside of all windows, there will not be ANR
4981TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004982 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004983 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4984 LOCATION_OUTSIDE_ALL_WINDOWS));
4985 ASSERT_TRUE(mDispatcher->waitForIdle());
4986 mFakePolicy->assertNotifyAnrWasNotCalled();
4987}
4988
4989// Since the focused window is paused, tapping on it should not produce any events
4990TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4991 mFocusedWindow->setPaused(true);
4992 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4993
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004994 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004995 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4996 FOCUSED_WINDOW_LOCATION));
4997
4998 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4999 ASSERT_TRUE(mDispatcher->waitForIdle());
5000 // Should not ANR because the window is paused, and touches shouldn't go to it
5001 mFakePolicy->assertNotifyAnrWasNotCalled();
5002
5003 mFocusedWindow->assertNoEvents();
5004 mUnfocusedWindow->assertNoEvents();
5005}
5006
5007/**
5008 * If a window is processing a motion event, and then a key event comes in, the key event should
5009 * not to to the focused window until the motion is processed.
5010 * If a different window becomes focused at this time, the key should go to that window instead.
5011 *
5012 * Warning!!!
5013 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5014 * and the injection timeout that we specify when injecting the key.
5015 * We must have the injection timeout (10ms) be smaller than
5016 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5017 *
5018 * If that value changes, this test should also change.
5019 */
5020TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5021 // Set a long ANR timeout to prevent it from triggering
5022 mFocusedWindow->setDispatchingTimeout(2s);
5023 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5024
5025 tapOnUnfocusedWindow();
5026 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5027 ASSERT_TRUE(downSequenceNum);
5028 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5029 ASSERT_TRUE(upSequenceNum);
5030 // Don't finish the events yet, and send a key
5031 // Injection will succeed because we will eventually give up and send the key to the focused
5032 // window even if motions are still being processed.
5033
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005034 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005035 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005036 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5037 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005038 // Key will not be sent to the window, yet, because the window is still processing events
5039 // and the key remains pending, waiting for the touch events to be processed
5040 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5041 ASSERT_FALSE(keySequenceNum);
5042
5043 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005044 mFocusedWindow->setFocusable(false);
5045 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005046 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005047 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005048
5049 // Focus events should precede the key events
5050 mUnfocusedWindow->consumeFocusEvent(true);
5051 mFocusedWindow->consumeFocusEvent(false);
5052
5053 // Finish the tap events, which should unblock dispatcher
5054 mUnfocusedWindow->finishEvent(*downSequenceNum);
5055 mUnfocusedWindow->finishEvent(*upSequenceNum);
5056
5057 // Now that all queues are cleared and no backlog in the connections, the key event
5058 // can finally go to the newly focused "mUnfocusedWindow".
5059 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5060 mFocusedWindow->assertNoEvents();
5061 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005062 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005063}
5064
5065// When the touch stream is split across 2 windows, and one of them does not respond,
5066// then ANR should be raised and the touch should be canceled for the unresponsive window.
5067// The other window should not be affected by that.
5068TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5069 // Touch Window 1
5070 NotifyMotionArgs motionArgs =
5071 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5072 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5073 mDispatcher->notifyMotion(&motionArgs);
5074 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5075 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5076
5077 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005078 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5079 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005080 mDispatcher->notifyMotion(&motionArgs);
5081
5082 const std::chrono::duration timeout =
5083 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005084 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005085
5086 mUnfocusedWindow->consumeMotionDown();
5087 mFocusedWindow->consumeMotionDown();
5088 // Focused window may or may not receive ACTION_MOVE
5089 // But it should definitely receive ACTION_CANCEL due to the ANR
5090 InputEvent* event;
5091 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5092 ASSERT_TRUE(moveOrCancelSequenceNum);
5093 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5094 ASSERT_NE(nullptr, event);
5095 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5096 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5097 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5098 mFocusedWindow->consumeMotionCancel();
5099 } else {
5100 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5101 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005102 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005103 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5104 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005105
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005106 mUnfocusedWindow->assertNoEvents();
5107 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005108 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005109}
5110
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005111/**
5112 * If we have no focused window, and a key comes in, we start the ANR timer.
5113 * The focused application should add a focused window before the timer runs out to prevent ANR.
5114 *
5115 * If the user touches another application during this time, the key should be dropped.
5116 * Next, if a new focused window comes in, without toggling the focused application,
5117 * then no ANR should occur.
5118 *
5119 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5120 * but in some cases the policy may not update the focused application.
5121 */
5122TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5123 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5124 std::make_shared<FakeApplicationHandle>();
5125 focusedApplication->setDispatchingTimeout(60ms);
5126 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5127 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5128 mFocusedWindow->setFocusable(false);
5129
5130 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5131 mFocusedWindow->consumeFocusEvent(false);
5132
5133 // Send a key. The ANR timer should start because there is no focused window.
5134 // 'focusedApplication' will get blamed if this timer completes.
5135 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005136 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005137 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005138 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5139 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005140 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005141
5142 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5143 // then the injected touches won't cause the focused event to get dropped.
5144 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5145 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5146 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5147 // For this test, it means that the key would get delivered to the window once it becomes
5148 // focused.
5149 std::this_thread::sleep_for(10ms);
5150
5151 // Touch unfocused window. This should force the pending key to get dropped.
5152 NotifyMotionArgs motionArgs =
5153 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5154 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5155 mDispatcher->notifyMotion(&motionArgs);
5156
5157 // We do not consume the motion right away, because that would require dispatcher to first
5158 // process (== drop) the key event, and by that time, ANR will be raised.
5159 // Set the focused window first.
5160 mFocusedWindow->setFocusable(true);
5161 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5162 setFocusedWindow(mFocusedWindow);
5163 mFocusedWindow->consumeFocusEvent(true);
5164 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5165 // to another application. This could be a bug / behaviour in the policy.
5166
5167 mUnfocusedWindow->consumeMotionDown();
5168
5169 ASSERT_TRUE(mDispatcher->waitForIdle());
5170 // Should not ANR because we actually have a focused window. It was just added too slowly.
5171 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5172}
5173
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005174// These tests ensure we cannot send touch events to a window that's positioned behind a window
5175// that has feature NO_INPUT_CHANNEL.
5176// Layout:
5177// Top (closest to user)
5178// mNoInputWindow (above all windows)
5179// mBottomWindow
5180// Bottom (furthest from user)
5181class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5182 virtual void SetUp() override {
5183 InputDispatcherTest::SetUp();
5184
5185 mApplication = std::make_shared<FakeApplicationHandle>();
5186 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5187 "Window without input channel", ADISPLAY_ID_DEFAULT,
5188 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5189
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005190 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005191 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5192 // It's perfectly valid for this window to not have an associated input channel
5193
5194 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5195 ADISPLAY_ID_DEFAULT);
5196 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5197
5198 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5199 }
5200
5201protected:
5202 std::shared_ptr<FakeApplicationHandle> mApplication;
5203 sp<FakeWindowHandle> mNoInputWindow;
5204 sp<FakeWindowHandle> mBottomWindow;
5205};
5206
5207TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5208 PointF touchedPoint = {10, 10};
5209
5210 NotifyMotionArgs motionArgs =
5211 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5212 ADISPLAY_ID_DEFAULT, {touchedPoint});
5213 mDispatcher->notifyMotion(&motionArgs);
5214
5215 mNoInputWindow->assertNoEvents();
5216 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5217 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5218 // and therefore should prevent mBottomWindow from receiving touches
5219 mBottomWindow->assertNoEvents();
5220}
5221
5222/**
5223 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5224 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5225 */
5226TEST_F(InputDispatcherMultiWindowOcclusionTests,
5227 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5228 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5229 "Window with input channel and NO_INPUT_CHANNEL",
5230 ADISPLAY_ID_DEFAULT);
5231
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005232 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005233 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5234 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5235
5236 PointF touchedPoint = {10, 10};
5237
5238 NotifyMotionArgs motionArgs =
5239 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5240 ADISPLAY_ID_DEFAULT, {touchedPoint});
5241 mDispatcher->notifyMotion(&motionArgs);
5242
5243 mNoInputWindow->assertNoEvents();
5244 mBottomWindow->assertNoEvents();
5245}
5246
Vishnu Nair958da932020-08-21 17:12:37 -07005247class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5248protected:
5249 std::shared_ptr<FakeApplicationHandle> mApp;
5250 sp<FakeWindowHandle> mWindow;
5251 sp<FakeWindowHandle> mMirror;
5252
5253 virtual void SetUp() override {
5254 InputDispatcherTest::SetUp();
5255 mApp = std::make_shared<FakeApplicationHandle>();
5256 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5257 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5258 mWindow->getToken());
5259 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5260 mWindow->setFocusable(true);
5261 mMirror->setFocusable(true);
5262 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5263 }
5264};
5265
5266TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5267 // Request focus on a mirrored window
5268 setFocusedWindow(mMirror);
5269
5270 // window gets focused
5271 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005272 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5273 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005274 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5275}
5276
5277// A focused & mirrored window remains focused only if the window and its mirror are both
5278// focusable.
5279TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5280 setFocusedWindow(mMirror);
5281
5282 // window gets focused
5283 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005284 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5285 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005286 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005287 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5288 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005289 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5290
5291 mMirror->setFocusable(false);
5292 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5293
5294 // window loses focus since one of the windows associated with the token in not focusable
5295 mWindow->consumeFocusEvent(false);
5296
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005297 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5298 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005299 mWindow->assertNoEvents();
5300}
5301
5302// A focused & mirrored window remains focused until the window and its mirror both become
5303// invisible.
5304TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5305 setFocusedWindow(mMirror);
5306
5307 // window gets focused
5308 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005309 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5310 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005311 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005312 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5313 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005314 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5315
5316 mMirror->setVisible(false);
5317 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5318
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005319 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5320 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005321 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005322 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5323 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005324 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5325
5326 mWindow->setVisible(false);
5327 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5328
5329 // window loses focus only after all windows associated with the token become invisible.
5330 mWindow->consumeFocusEvent(false);
5331
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005332 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5333 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005334 mWindow->assertNoEvents();
5335}
5336
5337// A focused & mirrored window remains focused until both windows are removed.
5338TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5339 setFocusedWindow(mMirror);
5340
5341 // window gets focused
5342 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005343 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5344 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005345 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005346 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5347 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005348 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5349
5350 // single window is removed but the window token remains focused
5351 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5352
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005353 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5354 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005355 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005356 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5357 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005358 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5359
5360 // Both windows are removed
5361 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5362 mWindow->consumeFocusEvent(false);
5363
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005364 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5365 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005366 mWindow->assertNoEvents();
5367}
5368
5369// Focus request can be pending until one window becomes visible.
5370TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5371 // Request focus on an invisible mirror.
5372 mWindow->setVisible(false);
5373 mMirror->setVisible(false);
5374 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5375 setFocusedWindow(mMirror);
5376
5377 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005378 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005379 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005380 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005381
5382 mMirror->setVisible(true);
5383 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5384
5385 // window gets focused
5386 mWindow->consumeFocusEvent(true);
5387 // window gets the pending key event
5388 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5389}
Prabir Pradhan99987712020-11-10 18:43:05 -08005390
5391class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5392protected:
5393 std::shared_ptr<FakeApplicationHandle> mApp;
5394 sp<FakeWindowHandle> mWindow;
5395 sp<FakeWindowHandle> mSecondWindow;
5396
5397 void SetUp() override {
5398 InputDispatcherTest::SetUp();
5399 mApp = std::make_shared<FakeApplicationHandle>();
5400 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5401 mWindow->setFocusable(true);
5402 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5403 mSecondWindow->setFocusable(true);
5404
5405 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5406 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5407
5408 setFocusedWindow(mWindow);
5409 mWindow->consumeFocusEvent(true);
5410 }
5411
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005412 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5413 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005414 mDispatcher->notifyPointerCaptureChanged(&args);
5415 }
5416
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005417 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5418 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005419 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005420 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5421 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005422 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005423 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005424 }
5425};
5426
5427TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5428 // Ensure that capture cannot be obtained for unfocused windows.
5429 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5430 mFakePolicy->assertSetPointerCaptureNotCalled();
5431 mSecondWindow->assertNoEvents();
5432
5433 // Ensure that capture can be enabled from the focus window.
5434 requestAndVerifyPointerCapture(mWindow, true);
5435
5436 // Ensure that capture cannot be disabled from a window that does not have capture.
5437 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5438 mFakePolicy->assertSetPointerCaptureNotCalled();
5439
5440 // Ensure that capture can be disabled from the window with capture.
5441 requestAndVerifyPointerCapture(mWindow, false);
5442}
5443
5444TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005445 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005446
5447 setFocusedWindow(mSecondWindow);
5448
5449 // Ensure that the capture disabled event was sent first.
5450 mWindow->consumeCaptureEvent(false);
5451 mWindow->consumeFocusEvent(false);
5452 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005453 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005454
5455 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005456 notifyPointerCaptureChanged({});
5457 notifyPointerCaptureChanged(request);
5458 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005459 mWindow->assertNoEvents();
5460 mSecondWindow->assertNoEvents();
5461 mFakePolicy->assertSetPointerCaptureNotCalled();
5462}
5463
5464TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005465 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005466
5467 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005468 notifyPointerCaptureChanged({});
5469 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005470
5471 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005472 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005473 mWindow->consumeCaptureEvent(false);
5474 mWindow->assertNoEvents();
5475}
5476
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005477TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5478 requestAndVerifyPointerCapture(mWindow, true);
5479
5480 // The first window loses focus.
5481 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005482 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005483 mWindow->consumeCaptureEvent(false);
5484
5485 // Request Pointer Capture from the second window before the notification from InputReader
5486 // arrives.
5487 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005488 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005489
5490 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005491 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005492
5493 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005494 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005495
5496 mSecondWindow->consumeFocusEvent(true);
5497 mSecondWindow->consumeCaptureEvent(true);
5498}
5499
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005500TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5501 // App repeatedly enables and disables capture.
5502 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5503 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5504 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5505 mFakePolicy->assertSetPointerCaptureCalled(false);
5506 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5507 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5508
5509 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5510 // first request is now stale, this should do nothing.
5511 notifyPointerCaptureChanged(firstRequest);
5512 mWindow->assertNoEvents();
5513
5514 // InputReader notifies that the second request was enabled.
5515 notifyPointerCaptureChanged(secondRequest);
5516 mWindow->consumeCaptureEvent(true);
5517}
5518
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005519class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5520protected:
5521 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005522
5523 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5524 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5525
5526 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5527 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5528
5529 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5530 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5531 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5532 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5533 MAXIMUM_OBSCURING_OPACITY);
5534
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005535 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005536 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005537 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005538
5539 sp<FakeWindowHandle> mTouchWindow;
5540
5541 virtual void SetUp() override {
5542 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005543 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005544 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5545 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5546 }
5547
5548 virtual void TearDown() override {
5549 InputDispatcherTest::TearDown();
5550 mTouchWindow.clear();
5551 }
5552
chaviw3277faf2021-05-19 16:45:23 -05005553 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5554 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005555 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005556 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005557 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005558 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005559 return window;
5560 }
5561
5562 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5563 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5564 sp<FakeWindowHandle> window =
5565 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5566 // Generate an arbitrary PID based on the UID
5567 window->setOwnerInfo(1777 + (uid % 10000), uid);
5568 return window;
5569 }
5570
5571 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5572 NotifyMotionArgs args =
5573 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5574 ADISPLAY_ID_DEFAULT, points);
5575 mDispatcher->notifyMotion(&args);
5576 }
5577};
5578
5579TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005580 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005581 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005582 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005583
5584 touch();
5585
5586 mTouchWindow->assertNoEvents();
5587}
5588
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005589TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005590 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5591 const sp<FakeWindowHandle>& w =
5592 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5593 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5594
5595 touch();
5596
5597 mTouchWindow->assertNoEvents();
5598}
5599
5600TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005601 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5602 const sp<FakeWindowHandle>& w =
5603 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5604 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5605
5606 touch();
5607
5608 w->assertNoEvents();
5609}
5610
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005611TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005612 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5613 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005614
5615 touch();
5616
5617 mTouchWindow->consumeAnyMotionDown();
5618}
5619
5620TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005621 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005622 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005623 w->setFrame(Rect(0, 0, 50, 50));
5624 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005625
5626 touch({PointF{100, 100}});
5627
5628 mTouchWindow->consumeAnyMotionDown();
5629}
5630
5631TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005632 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005633 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005634 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5635
5636 touch();
5637
5638 mTouchWindow->consumeAnyMotionDown();
5639}
5640
5641TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5642 const sp<FakeWindowHandle>& w =
5643 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5644 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005645
5646 touch();
5647
5648 mTouchWindow->consumeAnyMotionDown();
5649}
5650
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005651TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5652 const sp<FakeWindowHandle>& w =
5653 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5654 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5655
5656 touch();
5657
5658 w->assertNoEvents();
5659}
5660
5661/**
5662 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5663 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5664 * window, the occluding window will still receive ACTION_OUTSIDE event.
5665 */
5666TEST_F(InputDispatcherUntrustedTouchesTest,
5667 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5668 const sp<FakeWindowHandle>& w =
5669 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005670 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5672
5673 touch();
5674
5675 w->consumeMotionOutside();
5676}
5677
5678TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5679 const sp<FakeWindowHandle>& w =
5680 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005681 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005682 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5683
5684 touch();
5685
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005686 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005687}
5688
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005689TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005690 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005691 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5692 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005693 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5694
5695 touch();
5696
5697 mTouchWindow->consumeAnyMotionDown();
5698}
5699
5700TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5701 const sp<FakeWindowHandle>& w =
5702 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5703 MAXIMUM_OBSCURING_OPACITY);
5704 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005705
5706 touch();
5707
5708 mTouchWindow->consumeAnyMotionDown();
5709}
5710
5711TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005712 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005713 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5714 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005715 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5716
5717 touch();
5718
5719 mTouchWindow->assertNoEvents();
5720}
5721
5722TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5723 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5724 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005725 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5726 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005727 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005728 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5729 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005730 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5731
5732 touch();
5733
5734 mTouchWindow->assertNoEvents();
5735}
5736
5737TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5738 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5739 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005740 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5741 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005742 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005743 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5744 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005745 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5746
5747 touch();
5748
5749 mTouchWindow->consumeAnyMotionDown();
5750}
5751
5752TEST_F(InputDispatcherUntrustedTouchesTest,
5753 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5754 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005755 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5756 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005757 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005758 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5759 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005760 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5761
5762 touch();
5763
5764 mTouchWindow->consumeAnyMotionDown();
5765}
5766
5767TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5768 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005769 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5770 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005771 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005772 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5773 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005774 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005775
5776 touch();
5777
5778 mTouchWindow->assertNoEvents();
5779}
5780
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005781TEST_F(InputDispatcherUntrustedTouchesTest,
5782 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5783 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005784 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5785 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005786 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005787 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5788 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005789 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5790
5791 touch();
5792
5793 mTouchWindow->assertNoEvents();
5794}
5795
5796TEST_F(InputDispatcherUntrustedTouchesTest,
5797 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5798 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005799 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5800 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005801 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005802 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5803 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005804 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5805
5806 touch();
5807
5808 mTouchWindow->consumeAnyMotionDown();
5809}
5810
5811TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5812 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005813 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5814 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005815 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5816
5817 touch();
5818
5819 mTouchWindow->consumeAnyMotionDown();
5820}
5821
5822TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5823 const sp<FakeWindowHandle>& w =
5824 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5825 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5826
5827 touch();
5828
5829 mTouchWindow->consumeAnyMotionDown();
5830}
5831
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005832TEST_F(InputDispatcherUntrustedTouchesTest,
5833 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5834 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5835 const sp<FakeWindowHandle>& w =
5836 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5837 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5838
5839 touch();
5840
5841 mTouchWindow->assertNoEvents();
5842}
5843
5844TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5845 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5846 const sp<FakeWindowHandle>& w =
5847 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5848 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5849
5850 touch();
5851
5852 mTouchWindow->consumeAnyMotionDown();
5853}
5854
5855TEST_F(InputDispatcherUntrustedTouchesTest,
5856 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5857 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5858 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005859 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5860 OPACITY_ABOVE_THRESHOLD);
5861 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5862
5863 touch();
5864
5865 mTouchWindow->consumeAnyMotionDown();
5866}
5867
5868TEST_F(InputDispatcherUntrustedTouchesTest,
5869 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5870 const sp<FakeWindowHandle>& w1 =
5871 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5872 OPACITY_BELOW_THRESHOLD);
5873 const sp<FakeWindowHandle>& w2 =
5874 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5875 OPACITY_BELOW_THRESHOLD);
5876 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5877
5878 touch();
5879
5880 mTouchWindow->assertNoEvents();
5881}
5882
5883/**
5884 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5885 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5886 * (which alone would result in allowing touches) does not affect the blocking behavior.
5887 */
5888TEST_F(InputDispatcherUntrustedTouchesTest,
5889 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5890 const sp<FakeWindowHandle>& wB =
5891 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5892 OPACITY_BELOW_THRESHOLD);
5893 const sp<FakeWindowHandle>& wC =
5894 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5895 OPACITY_BELOW_THRESHOLD);
5896 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5897
5898 touch();
5899
5900 mTouchWindow->assertNoEvents();
5901}
5902
5903/**
5904 * This test is testing that a window from a different UID but with same application token doesn't
5905 * block the touch. Apps can share the application token for close UI collaboration for example.
5906 */
5907TEST_F(InputDispatcherUntrustedTouchesTest,
5908 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5909 const sp<FakeWindowHandle>& w =
5910 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5911 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005912 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5913
5914 touch();
5915
5916 mTouchWindow->consumeAnyMotionDown();
5917}
5918
arthurhungb89ccb02020-12-30 16:19:01 +08005919class InputDispatcherDragTests : public InputDispatcherTest {
5920protected:
5921 std::shared_ptr<FakeApplicationHandle> mApp;
5922 sp<FakeWindowHandle> mWindow;
5923 sp<FakeWindowHandle> mSecondWindow;
5924 sp<FakeWindowHandle> mDragWindow;
5925
5926 void SetUp() override {
5927 InputDispatcherTest::SetUp();
5928 mApp = std::make_shared<FakeApplicationHandle>();
5929 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5930 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005931
5932 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5933 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005934
5935 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5936 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5937 }
5938
5939 // Start performing drag, we will create a drag window and transfer touch to it.
5940 void performDrag() {
5941 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5942 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5943 {50, 50}))
5944 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5945
5946 // Window should receive motion event.
5947 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5948
5949 // The drag window covers the entire display
5950 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5951 mDispatcher->setInputWindows(
5952 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5953
5954 // Transfer touch focus to the drag window
5955 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5956 true /* isDragDrop */);
5957 mWindow->consumeMotionCancel();
5958 mDragWindow->consumeMotionDown();
5959 }
arthurhung6d4bed92021-03-17 11:59:33 +08005960
5961 // Start performing drag, we will create a drag window and transfer touch to it.
5962 void performStylusDrag() {
5963 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5964 injectMotionEvent(mDispatcher,
5965 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5966 AINPUT_SOURCE_STYLUS)
5967 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5968 .pointer(PointerBuilder(0,
5969 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5970 .x(50)
5971 .y(50))
5972 .build()));
5973 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5974
5975 // The drag window covers the entire display
5976 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5977 mDispatcher->setInputWindows(
5978 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5979
5980 // Transfer touch focus to the drag window
5981 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5982 true /* isDragDrop */);
5983 mWindow->consumeMotionCancel();
5984 mDragWindow->consumeMotionDown();
5985 }
arthurhungb89ccb02020-12-30 16:19:01 +08005986};
5987
5988TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5989 performDrag();
5990
5991 // Move on window.
5992 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5993 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5994 ADISPLAY_ID_DEFAULT, {50, 50}))
5995 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5996 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5997 mWindow->consumeDragEvent(false, 50, 50);
5998 mSecondWindow->assertNoEvents();
5999
6000 // Move to another window.
6001 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6002 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6003 ADISPLAY_ID_DEFAULT, {150, 50}))
6004 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6005 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6006 mWindow->consumeDragEvent(true, 150, 50);
6007 mSecondWindow->consumeDragEvent(false, 50, 50);
6008
6009 // Move back to original window.
6010 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6011 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6012 ADISPLAY_ID_DEFAULT, {50, 50}))
6013 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6014 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6015 mWindow->consumeDragEvent(false, 50, 50);
6016 mSecondWindow->consumeDragEvent(true, -50, 50);
6017
6018 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6019 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6020 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6021 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6022 mWindow->assertNoEvents();
6023 mSecondWindow->assertNoEvents();
6024}
6025
arthurhungf452d0b2021-01-06 00:19:52 +08006026TEST_F(InputDispatcherDragTests, DragAndDrop) {
6027 performDrag();
6028
6029 // Move on window.
6030 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6031 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6032 ADISPLAY_ID_DEFAULT, {50, 50}))
6033 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6034 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6035 mWindow->consumeDragEvent(false, 50, 50);
6036 mSecondWindow->assertNoEvents();
6037
6038 // Move to another window.
6039 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6040 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6041 ADISPLAY_ID_DEFAULT, {150, 50}))
6042 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6043 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6044 mWindow->consumeDragEvent(true, 150, 50);
6045 mSecondWindow->consumeDragEvent(false, 50, 50);
6046
6047 // drop to another window.
6048 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6049 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6050 {150, 50}))
6051 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6052 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6053 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6054 mWindow->assertNoEvents();
6055 mSecondWindow->assertNoEvents();
6056}
6057
arthurhung6d4bed92021-03-17 11:59:33 +08006058TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6059 performStylusDrag();
6060
6061 // Move on window and keep button pressed.
6062 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6063 injectMotionEvent(mDispatcher,
6064 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6065 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6066 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6067 .x(50)
6068 .y(50))
6069 .build()))
6070 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6071 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6072 mWindow->consumeDragEvent(false, 50, 50);
6073 mSecondWindow->assertNoEvents();
6074
6075 // Move to another window and release button, expect to drop item.
6076 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6077 injectMotionEvent(mDispatcher,
6078 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6079 .buttonState(0)
6080 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6081 .x(150)
6082 .y(50))
6083 .build()))
6084 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6085 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6086 mWindow->assertNoEvents();
6087 mSecondWindow->assertNoEvents();
6088 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6089
6090 // nothing to the window.
6091 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6092 injectMotionEvent(mDispatcher,
6093 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6094 .buttonState(0)
6095 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6096 .x(150)
6097 .y(50))
6098 .build()))
6099 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6100 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6101 mWindow->assertNoEvents();
6102 mSecondWindow->assertNoEvents();
6103}
6104
Arthur Hung6d0571e2021-04-09 20:18:16 +08006105TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6106 performDrag();
6107
6108 // Set second window invisible.
6109 mSecondWindow->setVisible(false);
6110 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6111
6112 // Move on window.
6113 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6114 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6115 ADISPLAY_ID_DEFAULT, {50, 50}))
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.
6122 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6123 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6124 ADISPLAY_ID_DEFAULT, {150, 50}))
6125 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6126 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6127 mWindow->consumeDragEvent(true, 150, 50);
6128 mSecondWindow->assertNoEvents();
6129
6130 // drop to another window.
6131 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6132 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6133 {150, 50}))
6134 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6135 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6136 mFakePolicy->assertDropTargetEquals(nullptr);
6137 mWindow->assertNoEvents();
6138 mSecondWindow->assertNoEvents();
6139}
6140
Vishnu Nair062a8672021-09-03 16:07:44 -07006141class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6142
6143TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6144 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6145 sp<FakeWindowHandle> window =
6146 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006147 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006148 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6149 window->setFocusable(true);
6150 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6151 setFocusedWindow(window);
6152 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6153
6154 // With the flag set, window should not get any input
6155 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6156 mDispatcher->notifyKey(&keyArgs);
6157 window->assertNoEvents();
6158
6159 NotifyMotionArgs motionArgs =
6160 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6161 ADISPLAY_ID_DEFAULT);
6162 mDispatcher->notifyMotion(&motionArgs);
6163 window->assertNoEvents();
6164
6165 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006166 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006167 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6168
6169 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6170 mDispatcher->notifyKey(&keyArgs);
6171 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6172
6173 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6174 ADISPLAY_ID_DEFAULT);
6175 mDispatcher->notifyMotion(&motionArgs);
6176 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6177 window->assertNoEvents();
6178}
6179
6180TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6181 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6182 std::make_shared<FakeApplicationHandle>();
6183 sp<FakeWindowHandle> obscuringWindow =
6184 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6185 ADISPLAY_ID_DEFAULT);
6186 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6187 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006188 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006189 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6190 sp<FakeWindowHandle> window =
6191 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006192 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006193 window->setOwnerInfo(222, 222);
6194 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6195 window->setFocusable(true);
6196 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, 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->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006213 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, 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, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6223 window->assertNoEvents();
6224}
6225
6226TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
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 // When the window is no longer obscured because it went on top, it should get input
6258 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6259
6260 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6261 mDispatcher->notifyKey(&keyArgs);
6262 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6263
6264 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6265 ADISPLAY_ID_DEFAULT);
6266 mDispatcher->notifyMotion(&motionArgs);
6267 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6268 window->assertNoEvents();
6269}
6270
Antonio Kantekf16f2832021-09-28 04:39:20 +00006271class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6272protected:
6273 std::shared_ptr<FakeApplicationHandle> mApp;
6274 sp<FakeWindowHandle> mWindow;
6275 sp<FakeWindowHandle> mSecondWindow;
6276
6277 void SetUp() override {
6278 InputDispatcherTest::SetUp();
6279
6280 mApp = std::make_shared<FakeApplicationHandle>();
6281 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6282 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006283 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006284 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6285 mSecondWindow->setFocusable(true);
6286
6287 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6288 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006289 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006290
6291 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
6292 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, INJECTOR_PID,
6293 INJECTOR_UID, /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006294 }
6295
Antonio Kantekea47acb2021-12-23 12:41:25 -08006296 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006297 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006298 mWindow->consumeTouchModeEvent(inTouchMode);
6299 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6300 }
6301};
6302
Antonio Kantek26defcf2022-02-08 01:12:27 +00006303TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006304 const WindowInfo& windowInfo = *mWindow->getInfo();
6305 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6306 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006307}
6308
Antonio Kantek26defcf2022-02-08 01:12:27 +00006309TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6310 const WindowInfo& windowInfo = *mWindow->getInfo();
6311 int32_t ownerPid = windowInfo.ownerPid;
6312 int32_t ownerUid = windowInfo.ownerUid;
6313 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6314 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6315 ownerUid, /* hasPermission */ false));
6316 mWindow->assertNoEvents();
6317 mSecondWindow->assertNoEvents();
6318}
6319
6320TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6321 const WindowInfo& windowInfo = *mWindow->getInfo();
6322 int32_t ownerPid = windowInfo.ownerPid;
6323 int32_t ownerUid = windowInfo.ownerUid;
6324 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6325 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6326 /* hasPermission */ true);
6327}
6328
Antonio Kantekf16f2832021-09-28 04:39:20 +00006329TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006330 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006331 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6332 windowInfo.ownerPid, windowInfo.ownerUid,
6333 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006334 mWindow->assertNoEvents();
6335 mSecondWindow->assertNoEvents();
6336}
6337
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006338class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6339public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006340 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006341 std::shared_ptr<FakeApplicationHandle> application =
6342 std::make_shared<FakeApplicationHandle>();
6343 std::string name = "Fake Spy ";
6344 name += std::to_string(mSpyCount++);
6345 sp<FakeWindowHandle> spy =
6346 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006347 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006348 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006349 return spy;
6350 }
6351
6352 sp<FakeWindowHandle> createForeground() {
6353 std::shared_ptr<FakeApplicationHandle> application =
6354 std::make_shared<FakeApplicationHandle>();
6355 sp<FakeWindowHandle> window =
6356 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006357 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006358 return window;
6359 }
6360
6361private:
6362 int mSpyCount{0};
6363};
6364
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006365using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006366/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006367 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6368 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006369TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6370 ScopedSilentDeath _silentDeath;
6371
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006372 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006373 spy->setTrustedOverlay(false);
6374 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6375 ".* not a trusted overlay");
6376}
6377
6378/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006379 * Input injection into a display with a spy window but no foreground windows should succeed.
6380 */
6381TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006382 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006383 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6384
6385 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6386 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6387 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6388 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6389}
6390
6391/**
6392 * Verify the order in which different input windows receive events. The touched foreground window
6393 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6394 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6395 * receive events before ones belows it.
6396 *
6397 * Here, we set up a scenario with four windows in the following Z order from the top:
6398 * spy1, spy2, window, spy3.
6399 * We then inject an event and verify that the foreground "window" receives it first, followed by
6400 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6401 * window.
6402 */
6403TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6404 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006405 auto spy1 = createSpy();
6406 auto spy2 = createSpy();
6407 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006408 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6409 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6410 const size_t numChannels = channels.size();
6411
Michael Wright8e9a8562022-02-09 13:44:29 +00006412 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006413 if (!epollFd.ok()) {
6414 FAIL() << "Failed to create epoll fd";
6415 }
6416
6417 for (size_t i = 0; i < numChannels; i++) {
6418 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6419 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6420 FAIL() << "Failed to add fd to epoll";
6421 }
6422 }
6423
6424 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6425 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6426 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6427
6428 std::vector<size_t> eventOrder;
6429 std::vector<struct epoll_event> events(numChannels);
6430 for (;;) {
6431 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6432 (100ms).count());
6433 if (nFds < 0) {
6434 FAIL() << "Failed to call epoll_wait";
6435 }
6436 if (nFds == 0) {
6437 break; // epoll_wait timed out
6438 }
6439 for (int i = 0; i < nFds; i++) {
6440 ASSERT_EQ(EPOLLIN, events[i].events);
6441 eventOrder.push_back(events[i].data.u64);
6442 channels[i]->consumeMotionDown();
6443 }
6444 }
6445
6446 // Verify the order in which the events were received.
6447 EXPECT_EQ(3u, eventOrder.size());
6448 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6449 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6450 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6451}
6452
6453/**
6454 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6455 */
6456TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6457 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006458 auto spy = createSpy();
6459 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006460 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6461
6462 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6463 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6464 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6465 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6466 spy->assertNoEvents();
6467}
6468
6469/**
6470 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6471 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6472 * to the window.
6473 */
6474TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6475 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006476 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006477 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6478 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6479
6480 // Inject an event outside the spy window's touchable region.
6481 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6482 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6483 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6484 window->consumeMotionDown();
6485 spy->assertNoEvents();
6486 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6487 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6488 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6489 window->consumeMotionUp();
6490 spy->assertNoEvents();
6491
6492 // Inject an event inside the spy window's touchable region.
6493 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6494 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6495 {5, 10}))
6496 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6497 window->consumeMotionDown();
6498 spy->consumeMotionDown();
6499}
6500
6501/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006502 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006503 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006504 */
6505TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6506 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006507 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006508 auto spy = createSpy();
6509 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006510 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006511 spy->setFrame(Rect{0, 0, 20, 20});
6512 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6513
6514 // Inject an event outside the spy window's frame and touchable region.
6515 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006516 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6517 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006518 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6519 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006520 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006521}
6522
6523/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006524 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6525 * any other windows - including other spy windows - will also be cancelled.
6526 */
6527TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6528 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006529 auto spy1 = createSpy();
6530 auto spy2 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006531 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6532
6533 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6534 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6535 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6536 window->consumeMotionDown();
6537 spy1->consumeMotionDown();
6538 spy2->consumeMotionDown();
6539
6540 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006541 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006542 spy2->assertNoEvents();
6543 spy1->consumeMotionCancel();
6544 window->consumeMotionCancel();
6545
6546 // The rest of the gesture should only be sent to the second spy window.
6547 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6548 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6549 ADISPLAY_ID_DEFAULT))
6550 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6551 spy2->consumeMotionMove();
6552 spy1->assertNoEvents();
6553 window->assertNoEvents();
6554}
6555
6556/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006557 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
6558 * in the middle of the gesture.
6559 */
6560TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
6561 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006562 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006563 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6564
6565 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6566 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6567 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6568 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6569 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6570
6571 window->releaseChannel();
6572
6573 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6574
6575 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6576 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6577 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6578 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6579}
6580
6581/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006582 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
6583 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006584 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006585TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006586 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006587 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006588
6589 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6590
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006591 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006592 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6593 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6594 {100, 200}))
6595 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006596 spy->consumeMotionDown();
6597 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006598
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006599 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006600 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006601 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006602
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006603 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006604 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006605 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006606 .displayId(ADISPLAY_ID_DEFAULT)
6607 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6608 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6609 .x(100)
6610 .y(200))
6611 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6612 .build();
6613 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6614 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6615 InputEventInjectionSync::WAIT_FOR_RESULT))
6616 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6617
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006618 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6619
6620 // Third finger goes down outside all windows, so injection should fail.
6621 const MotionEvent thirdFingerDownEvent =
Prabir Pradhanb60b1dc2022-03-15 14:02:35 +00006622 MotionEventBuilder(POINTER_2_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006623 .displayId(ADISPLAY_ID_DEFAULT)
6624 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6625 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6626 .x(100)
6627 .y(200))
6628 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6629 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
6630 .build();
6631 ASSERT_EQ(InputEventInjectionResult::FAILED,
6632 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
6633 InputEventInjectionSync::WAIT_FOR_RESULT))
6634 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6635
6636 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006637 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006638}
6639
6640/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006641 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6642 * pointers that are down within its bounds.
6643 */
6644TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6645 auto windowLeft = createForeground();
6646 windowLeft->setFrame({0, 0, 100, 200});
6647 auto windowRight = createForeground();
6648 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006649 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006650 spy->setFrame({0, 0, 200, 200});
6651 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6652
6653 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6654 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6655 {50, 50}))
6656 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6657 windowLeft->consumeMotionDown();
6658 spy->consumeMotionDown();
6659
6660 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006661 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006662 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6663 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6664 .pointer(
6665 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6666 .build();
6667 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6668 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6669 InputEventInjectionSync::WAIT_FOR_RESULT))
6670 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6671 windowRight->consumeMotionDown();
6672 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6673}
6674
6675/**
6676 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6677 * the spy should receive the second pointer with ACTION_DOWN.
6678 */
6679TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6680 auto window = createForeground();
6681 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006682 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006683 spyRight->setFrame({100, 0, 200, 200});
6684 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6685
6686 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6687 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6688 {50, 50}))
6689 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6690 window->consumeMotionDown();
6691 spyRight->assertNoEvents();
6692
6693 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006694 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006695 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6696 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6697 .pointer(
6698 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6699 .build();
6700 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6701 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6702 InputEventInjectionSync::WAIT_FOR_RESULT))
6703 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6704 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6705 spyRight->consumeMotionDown();
6706}
6707
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006708/**
6709 * The spy window should not be able to affect whether or not touches are split. Only the foreground
6710 * windows should be allowed to control split touch.
6711 */
6712TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006713 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006714 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006715 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006716 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006717
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006718 auto window = createForeground();
6719 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006720
6721 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6722
6723 // First finger down, no window touched.
6724 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6725 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6726 {100, 200}))
6727 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6728 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6729 window->assertNoEvents();
6730
6731 // Second finger down on window, the window should receive touch down.
6732 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006733 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006734 .displayId(ADISPLAY_ID_DEFAULT)
6735 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6736 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6737 .x(100)
6738 .y(200))
6739 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6740 .build();
6741 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6742 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6743 InputEventInjectionSync::WAIT_FOR_RESULT))
6744 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6745
6746 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6747 spy->consumeMotionPointerDown(1 /* pointerIndex */);
6748}
6749
6750/**
6751 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
6752 * do not receive key events.
6753 */
6754TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006755 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006756 spy->setFocusable(false);
6757
6758 auto window = createForeground();
6759 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6760 setFocusedWindow(window);
6761 window->consumeFocusEvent(true);
6762
6763 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6764 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6765 window->consumeKeyDown(ADISPLAY_ID_NONE);
6766
6767 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6768 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6769 window->consumeKeyUp(ADISPLAY_ID_NONE);
6770
6771 spy->assertNoEvents();
6772}
6773
Prabir Pradhand65552b2021-10-07 11:23:50 -07006774class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6775public:
6776 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6777 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6778 std::make_shared<FakeApplicationHandle>();
6779 sp<FakeWindowHandle> overlay =
6780 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6781 ADISPLAY_ID_DEFAULT);
6782 overlay->setFocusable(false);
6783 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006784 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006785 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006786 overlay->setTrustedOverlay(true);
6787
6788 std::shared_ptr<FakeApplicationHandle> application =
6789 std::make_shared<FakeApplicationHandle>();
6790 sp<FakeWindowHandle> window =
6791 new FakeWindowHandle(application, mDispatcher, "Application window",
6792 ADISPLAY_ID_DEFAULT);
6793 window->setFocusable(true);
6794 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006795
6796 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6797 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6798 setFocusedWindow(window);
6799 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6800 return {std::move(overlay), std::move(window)};
6801 }
6802
6803 void sendFingerEvent(int32_t action) {
6804 NotifyMotionArgs motionArgs =
6805 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6806 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6807 mDispatcher->notifyMotion(&motionArgs);
6808 }
6809
6810 void sendStylusEvent(int32_t action) {
6811 NotifyMotionArgs motionArgs =
6812 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6813 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6814 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6815 mDispatcher->notifyMotion(&motionArgs);
6816 }
6817};
6818
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006819using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
6820
6821TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
6822 ScopedSilentDeath _silentDeath;
6823
Prabir Pradhand65552b2021-10-07 11:23:50 -07006824 auto [overlay, window] = setupStylusOverlayScenario();
6825 overlay->setTrustedOverlay(false);
6826 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6827 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6828 ".* not a trusted overlay");
6829}
6830
6831TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6832 auto [overlay, window] = setupStylusOverlayScenario();
6833 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6834
6835 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6836 overlay->consumeMotionDown();
6837 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6838 overlay->consumeMotionUp();
6839
6840 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6841 window->consumeMotionDown();
6842 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6843 window->consumeMotionUp();
6844
6845 overlay->assertNoEvents();
6846 window->assertNoEvents();
6847}
6848
6849TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6850 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006851 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006852 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6853
6854 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6855 overlay->consumeMotionDown();
6856 window->consumeMotionDown();
6857 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6858 overlay->consumeMotionUp();
6859 window->consumeMotionUp();
6860
6861 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6862 window->consumeMotionDown();
6863 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6864 window->consumeMotionUp();
6865
6866 overlay->assertNoEvents();
6867 window->assertNoEvents();
6868}
6869
Garfield Tane84e6f92019-08-29 17:28:41 -07006870} // namespace android::inputdispatcher