blob: 0dd990e46c443a3d0adcc339133bb477748b0e4d [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>
Garfield Tan1c7bc862020-01-28 13:24:04 -080020#include <android-base/stringprintf.h>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070021#include <android-base/thread_annotations.h>
Robert Carr803535b2018-08-02 16:38:15 -070022#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080023#include <gtest/gtest.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100024#include <input/Input.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080025#include <linux/input.h>
Prabir Pradhan07e05b62021-11-19 03:57:24 -080026#include <sys/epoll.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100027
Garfield Tan1c7bc862020-01-28 13:24:04 -080028#include <cinttypes>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070029#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080030#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080031#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080032
Garfield Tan1c7bc862020-01-28 13:24:04 -080033using android::base::StringPrintf;
chaviw3277faf2021-05-19 16:45:23 -050034using android::gui::FocusRequest;
35using android::gui::TouchOcclusionMode;
36using android::gui::WindowInfo;
37using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080038using android::os::InputEventInjectionResult;
39using android::os::InputEventInjectionSync;
Michael Wright44753b12020-07-08 13:48:11 +010040using namespace android::flag_operators;
Garfield Tan1c7bc862020-01-28 13:24:04 -080041
Garfield Tane84e6f92019-08-29 17:28:41 -070042namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080043
44// An arbitrary time value.
45static const nsecs_t ARBITRARY_TIME = 1234;
46
47// An arbitrary device id.
48static const int32_t DEVICE_ID = 1;
49
Jeff Brownf086ddb2014-02-11 14:28:48 -080050// An arbitrary display id.
Arthur Hungabbb9d82021-09-01 14:52:30 +000051static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
52static constexpr int32_t SECOND_DISPLAY_ID = 1;
Jeff Brownf086ddb2014-02-11 14:28:48 -080053
Michael Wrightd02c5b62014-02-10 15:10:22 -080054// An arbitrary injector pid / uid pair that has permission to inject events.
55static const int32_t INJECTOR_PID = 999;
56static const int32_t INJECTOR_UID = 1001;
57
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000058// An arbitrary pid of the gesture monitor window
59static constexpr int32_t MONITOR_PID = 2001;
60
chaviwd1c23182019-12-20 18:44:56 -080061struct PointF {
62 float x;
63 float y;
64};
Michael Wrightd02c5b62014-02-10 15:10:22 -080065
Gang Wang342c9272020-01-13 13:15:04 -050066/**
67 * Return a DOWN key event with KEYCODE_A.
68 */
69static KeyEvent getTestKeyEvent() {
70 KeyEvent event;
71
Garfield Tanfbe732e2020-01-24 11:26:14 -080072 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
73 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
74 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050075 return event;
76}
77
Siarhei Vishniakouca205502021-07-16 21:31:58 +000078static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
79 ASSERT_EQ(expectedAction, receivedAction)
80 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
81 << MotionEvent::actionToString(receivedAction);
82}
83
Michael Wrightd02c5b62014-02-10 15:10:22 -080084// --- FakeInputDispatcherPolicy ---
85
86class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
87 InputDispatcherConfiguration mConfig;
88
89protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100090 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -080091
92public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100093 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +080094
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080095 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -070096 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
97 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
98 EXPECT_EQ(event.getDisplayId(), args.displayId);
99
100 const auto& keyEvent = static_cast<const KeyEvent&>(event);
101 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
102 EXPECT_EQ(keyEvent.getAction(), args.action);
103 });
Jackal Guof9696682018-10-05 12:23:23 +0800104 }
105
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700106 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
107 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
108 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
109 EXPECT_EQ(event.getDisplayId(), args.displayId);
110
111 const auto& motionEvent = static_cast<const MotionEvent&>(event);
112 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
113 EXPECT_EQ(motionEvent.getAction(), args.action);
114 EXPECT_EQ(motionEvent.getX(0), point.x);
115 EXPECT_EQ(motionEvent.getY(0), point.y);
116 EXPECT_EQ(motionEvent.getRawX(0), point.x);
117 EXPECT_EQ(motionEvent.getRawY(0), point.y);
118 });
Jackal Guof9696682018-10-05 12:23:23 +0800119 }
120
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700121 void assertFilterInputEventWasNotCalled() {
122 std::scoped_lock lock(mLock);
123 ASSERT_EQ(nullptr, mFilteredEvent);
124 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800125
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800126 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700127 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800128 ASSERT_TRUE(mConfigurationChangedTime)
129 << "Timed out waiting for configuration changed call";
130 ASSERT_EQ(*mConfigurationChangedTime, when);
131 mConfigurationChangedTime = std::nullopt;
132 }
133
134 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700135 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800136 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800137 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800138 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
139 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
140 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
141 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
142 mLastNotifySwitch = std::nullopt;
143 }
144
chaviwfd6d3512019-03-25 13:23:49 -0700145 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700146 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800147 ASSERT_EQ(touchedToken, mOnPointerDownToken);
148 mOnPointerDownToken.clear();
149 }
150
151 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700152 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800153 ASSERT_TRUE(mOnPointerDownToken == nullptr)
154 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700155 }
156
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700157 // This function must be called soon after the expected ANR timer starts,
158 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500159 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700160 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500161 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
162 std::shared_ptr<InputApplicationHandle> application;
163 { // acquire lock
164 std::unique_lock lock(mLock);
165 android::base::ScopedLockAssertion assumeLocked(mLock);
166 ASSERT_NO_FATAL_FAILURE(
167 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
168 } // release lock
169 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700170 }
171
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000172 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
173 const sp<IBinder>& expectedConnectionToken) {
174 sp<IBinder> connectionToken = getUnresponsiveWindowToken(timeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500175 ASSERT_EQ(expectedConnectionToken, connectionToken);
176 }
177
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000178 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
179 sp<IBinder> connectionToken = getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500180 ASSERT_EQ(expectedConnectionToken, connectionToken);
181 }
182
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000183 void assertNotifyMonitorUnresponsiveWasCalled(std::chrono::nanoseconds timeout) {
184 int32_t pid = getUnresponsiveMonitorPid(timeout);
185 ASSERT_EQ(MONITOR_PID, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500186 }
187
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000188 void assertNotifyMonitorResponsiveWasCalled() {
189 int32_t pid = getResponsiveMonitorPid();
190 ASSERT_EQ(MONITOR_PID, pid);
191 }
192
193 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500194 std::unique_lock lock(mLock);
195 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000196 return getAnrTokenLockedInterruptible(timeout, mAnrWindowTokens, lock);
197 }
198
199 sp<IBinder> getResponsiveWindowToken() {
200 std::unique_lock lock(mLock);
201 android::base::ScopedLockAssertion assumeLocked(mLock);
202 return getAnrTokenLockedInterruptible(0s, mResponsiveWindowTokens, lock);
203 }
204
205 int32_t getUnresponsiveMonitorPid(std::chrono::nanoseconds timeout) {
206 std::unique_lock lock(mLock);
207 android::base::ScopedLockAssertion assumeLocked(mLock);
208 return getAnrTokenLockedInterruptible(timeout, mAnrMonitorPids, lock);
209 }
210
211 int32_t getResponsiveMonitorPid() {
212 std::unique_lock lock(mLock);
213 android::base::ScopedLockAssertion assumeLocked(mLock);
214 return getAnrTokenLockedInterruptible(0s, mResponsiveMonitorPids, lock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500215 }
216
217 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
218 // for a specific container to become non-empty. When the container is non-empty, return the
219 // first entry from the container and erase it.
220 template <class T>
221 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
222 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700223 // If there is an ANR, Dispatcher won't be idle because there are still events
224 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
225 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500226 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
227 // to provide it some time to act. 100ms seems reasonable.
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800228 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
229 const std::chrono::time_point start = std::chrono::steady_clock::now();
230 std::optional<T> token =
231 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
232 if (!token.has_value()) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500233 ADD_FAILURE() << "Did not receive the ANR callback";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000234 return {};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700235 }
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800236
237 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700238 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
239 // the dispatcher started counting before this function was called
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700240 if (std::chrono::abs(timeout - waited) > 100ms) {
241 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
242 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
243 << "ms, but waited "
244 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
245 << "ms instead";
246 }
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800247 return *token;
248 }
249
250 template <class T>
251 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
252 std::queue<T>& storage,
253 std::unique_lock<std::mutex>& lock,
254 std::condition_variable& condition)
255 REQUIRES(mLock) {
256 condition.wait_for(lock, timeout,
257 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
258 if (storage.empty()) {
259 ADD_FAILURE() << "Did not receive the expected callback";
260 return std::nullopt;
261 }
262 T item = storage.front();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500263 storage.pop();
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800264 return std::make_optional(item);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700265 }
266
267 void assertNotifyAnrWasNotCalled() {
268 std::scoped_lock lock(mLock);
269 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000270 ASSERT_TRUE(mAnrWindowTokens.empty());
271 ASSERT_TRUE(mAnrMonitorPids.empty());
272 ASSERT_TRUE(mResponsiveWindowTokens.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500273 << "ANR was not called, but please also consume the 'connection is responsive' "
274 "signal";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000275 ASSERT_TRUE(mResponsiveMonitorPids.empty())
276 << "Monitor ANR was not called, but please also consume the 'monitor is responsive'"
277 " signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700278 }
279
Garfield Tan1c7bc862020-01-28 13:24:04 -0800280 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
281 mConfig.keyRepeatTimeout = timeout;
282 mConfig.keyRepeatDelay = delay;
283 }
284
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000285 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800286 std::unique_lock lock(mLock);
287 base::ScopedLockAssertion assumeLocked(mLock);
288
289 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
290 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000291 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800292 enabled;
293 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000294 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
295 << ") to be called.";
296 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800297 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000298 auto request = *mPointerCaptureRequest;
299 mPointerCaptureRequest.reset();
300 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800301 }
302
303 void assertSetPointerCaptureNotCalled() {
304 std::unique_lock lock(mLock);
305 base::ScopedLockAssertion assumeLocked(mLock);
306
307 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000308 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800309 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000310 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800311 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000312 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800313 }
314
arthurhungf452d0b2021-01-06 00:19:52 +0800315 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
316 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800317 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800318 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800319 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800320 }
321
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800322 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
323 std::unique_lock lock(mLock);
324 base::ScopedLockAssertion assumeLocked(mLock);
325 std::optional<sp<IBinder>> receivedToken =
326 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
327 mNotifyInputChannelBroken);
328 ASSERT_TRUE(receivedToken.has_value());
329 ASSERT_EQ(token, *receivedToken);
330 }
331
Michael Wrightd02c5b62014-02-10 15:10:22 -0800332private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700333 std::mutex mLock;
334 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
335 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
336 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
337 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800338
Prabir Pradhan99987712020-11-10 18:43:05 -0800339 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000340
341 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800342
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700343 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700344 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000345 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
346 std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
347 std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
348 std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700349 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800350 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
351 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700352
arthurhungf452d0b2021-01-06 00:19:52 +0800353 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800354 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800355
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600356 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700357 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800358 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800359 }
360
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000361 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700362 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000363 mAnrWindowTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700364 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500365 }
366
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000367 void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500368 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000369 mAnrMonitorPids.push(pid);
370 mNotifyAnr.notify_all();
371 }
372
373 void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
374 std::scoped_lock lock(mLock);
375 mResponsiveWindowTokens.push(connectionToken);
376 mNotifyAnr.notify_all();
377 }
378
379 void notifyMonitorResponsive(int32_t pid) override {
380 std::scoped_lock lock(mLock);
381 mResponsiveMonitorPids.push(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];
561 for (int i = 0; i <= MAX_POINTERS; i++) {
562 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,
Garfield Tan00f511d2019-06-12 16:55:40 -0700588 AMOTION_EVENT_ACTION_POINTER_DOWN |
589 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700590 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
591 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700592 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500593 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800594 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700595 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800596 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800597 << "Should reject motion events with pointer down index too large.";
598
Garfield Tanfbe732e2020-01-24 11:26:14 -0800599 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700600 AMOTION_EVENT_ACTION_POINTER_DOWN |
601 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700602 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
603 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700604 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500605 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800606 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700607 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800608 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800609 << "Should reject motion events with pointer down index too small.";
610
611 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800612 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700613 AMOTION_EVENT_ACTION_POINTER_UP |
614 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700615 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
616 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700617 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500618 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800619 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700620 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800621 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 << "Should reject motion events with pointer up index too large.";
623
Garfield Tanfbe732e2020-01-24 11:26:14 -0800624 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700625 AMOTION_EVENT_ACTION_POINTER_UP |
626 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700627 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
628 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700629 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500630 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800631 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700632 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800633 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800634 << "Should reject motion events with pointer up index too small.";
635
636 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800637 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
638 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700639 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700640 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
641 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700642 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800643 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700644 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800645 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800646 << "Should reject motion events with 0 pointers.";
647
Garfield Tanfbe732e2020-01-24 11:26:14 -0800648 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
649 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700650 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700651 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
652 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700653 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800654 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700655 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800656 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800657 << "Should reject motion events with more than MAX_POINTERS pointers.";
658
659 // Rejects motion events with invalid pointer ids.
660 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800661 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
662 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700663 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700664 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
665 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700666 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800667 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700668 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800669 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800670 << "Should reject motion events with pointer ids less than 0.";
671
672 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800673 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
674 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700675 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700676 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
677 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700678 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800679 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700680 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800681 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800682 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
683
684 // Rejects motion events with duplicate pointer ids.
685 pointerProperties[0].id = 1;
686 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800687 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
688 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700689 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700690 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
691 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700692 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800693 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700694 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800695 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800696 << "Should reject motion events with duplicate pointer ids.";
697}
698
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800699/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
700
701TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
702 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800703 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800704 mDispatcher->notifyConfigurationChanged(&args);
705 ASSERT_TRUE(mDispatcher->waitForIdle());
706
707 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
708}
709
710TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800711 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
712 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800713 mDispatcher->notifySwitch(&args);
714
715 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
716 args.policyFlags |= POLICY_FLAG_TRUSTED;
717 mFakePolicy->assertNotifySwitchWasCalled(args);
718}
719
Arthur Hungb92218b2018-08-14 12:00:21 +0800720// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700721static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700722// Default input dispatching timeout if there is no focused application or paused window
723// from which to determine an appropriate dispatching timeout.
724static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
725 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
726 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800727
728class FakeApplicationHandle : public InputApplicationHandle {
729public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700730 FakeApplicationHandle() {
731 mInfo.name = "Fake Application";
732 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500733 mInfo.dispatchingTimeoutMillis =
734 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700735 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800736 virtual ~FakeApplicationHandle() {}
737
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000738 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700739
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500740 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
741 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700742 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800743};
744
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800745class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800746public:
Garfield Tan15601662020-09-22 15:32:38 -0700747 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800748 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700749 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800750 }
751
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800752 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700753 InputEvent* event;
754 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
755 if (!consumeSeq) {
756 return nullptr;
757 }
758 finishEvent(*consumeSeq);
759 return event;
760 }
761
762 /**
763 * Receive an event without acknowledging it.
764 * Return the sequence number that could later be used to send finished signal.
765 */
766 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800767 uint32_t consumeSeq;
768 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800769
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800770 std::chrono::time_point start = std::chrono::steady_clock::now();
771 status_t status = WOULD_BLOCK;
772 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800773 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800774 &event);
775 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
776 if (elapsed > 100ms) {
777 break;
778 }
779 }
780
781 if (status == WOULD_BLOCK) {
782 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700783 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800784 }
785
786 if (status != OK) {
787 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700788 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800789 }
790 if (event == nullptr) {
791 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700792 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800793 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700794 if (outEvent != nullptr) {
795 *outEvent = event;
796 }
797 return consumeSeq;
798 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800799
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700800 /**
801 * To be used together with "receiveEvent" to complete the consumption of an event.
802 */
803 void finishEvent(uint32_t consumeSeq) {
804 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
805 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800806 }
807
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000808 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
809 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
810 ASSERT_EQ(OK, status);
811 }
812
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000813 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
814 std::optional<int32_t> expectedDisplayId,
815 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800816 InputEvent* event = consume();
817
818 ASSERT_NE(nullptr, event) << mName.c_str()
819 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800820 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700821 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800822 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800823
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000824 if (expectedDisplayId.has_value()) {
825 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
826 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800827
Tiger Huang8664f8c2018-10-11 19:14:35 +0800828 switch (expectedEventType) {
829 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800830 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
831 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000832 if (expectedFlags.has_value()) {
833 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
834 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800835 break;
836 }
837 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800838 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000839 assertMotionAction(expectedAction, motionEvent.getAction());
840
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000841 if (expectedFlags.has_value()) {
842 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
843 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800844 break;
845 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100846 case AINPUT_EVENT_TYPE_FOCUS: {
847 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
848 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800849 case AINPUT_EVENT_TYPE_CAPTURE: {
850 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
851 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000852 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
853 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
854 }
arthurhungb89ccb02020-12-30 16:19:01 +0800855 case AINPUT_EVENT_TYPE_DRAG: {
856 FAIL() << "Use 'consumeDragEvent' for DRAG events";
857 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800858 default: {
859 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
860 }
861 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800862 }
863
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100864 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
865 InputEvent* event = consume();
866 ASSERT_NE(nullptr, event) << mName.c_str()
867 << ": consumer should have returned non-NULL event.";
868 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
869 << "Got " << inputEventTypeToString(event->getType())
870 << " event instead of FOCUS event";
871
872 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
873 << mName.c_str() << ": event displayId should always be NONE.";
874
875 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
876 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100877 }
878
Prabir Pradhan99987712020-11-10 18:43:05 -0800879 void consumeCaptureEvent(bool hasCapture) {
880 const InputEvent* event = consume();
881 ASSERT_NE(nullptr, event) << mName.c_str()
882 << ": consumer should have returned non-NULL event.";
883 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
884 << "Got " << inputEventTypeToString(event->getType())
885 << " event instead of CAPTURE event";
886
887 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
888 << mName.c_str() << ": event displayId should always be NONE.";
889
890 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
891 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
892 }
893
arthurhungb89ccb02020-12-30 16:19:01 +0800894 void consumeDragEvent(bool isExiting, float x, float y) {
895 const InputEvent* event = consume();
896 ASSERT_NE(nullptr, event) << mName.c_str()
897 << ": consumer should have returned non-NULL event.";
898 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
899 << "Got " << inputEventTypeToString(event->getType())
900 << " event instead of DRAG event";
901
902 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
903 << mName.c_str() << ": event displayId should always be NONE.";
904
905 const auto& dragEvent = static_cast<const DragEvent&>(*event);
906 EXPECT_EQ(isExiting, dragEvent.isExiting());
907 EXPECT_EQ(x, dragEvent.getX());
908 EXPECT_EQ(y, dragEvent.getY());
909 }
910
Antonio Kantekf16f2832021-09-28 04:39:20 +0000911 void consumeTouchModeEvent(bool inTouchMode) {
912 const InputEvent* event = consume();
913 ASSERT_NE(nullptr, event) << mName.c_str()
914 << ": consumer should have returned non-NULL event.";
915 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
916 << "Got " << inputEventTypeToString(event->getType())
917 << " event instead of TOUCH_MODE event";
918
919 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
920 << mName.c_str() << ": event displayId should always be NONE.";
921 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
922 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
923 }
924
chaviwd1c23182019-12-20 18:44:56 -0800925 void assertNoEvents() {
926 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700927 if (event == nullptr) {
928 return;
929 }
930 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
931 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
932 ADD_FAILURE() << "Received key event "
933 << KeyEvent::actionToString(keyEvent.getAction());
934 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
935 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
936 ADD_FAILURE() << "Received motion event "
937 << MotionEvent::actionToString(motionEvent.getAction());
938 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
939 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
940 ADD_FAILURE() << "Received focus event, hasFocus = "
941 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800942 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
943 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
944 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
945 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000946 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
947 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
948 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
949 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700950 }
951 FAIL() << mName.c_str()
952 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800953 }
954
955 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
956
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800957 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
958
chaviwd1c23182019-12-20 18:44:56 -0800959protected:
960 std::unique_ptr<InputConsumer> mConsumer;
961 PreallocatedInputEventFactory mEventFactory;
962
963 std::string mName;
964};
965
chaviw3277faf2021-05-19 16:45:23 -0500966class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800967public:
968 static const int32_t WIDTH = 600;
969 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800970
Chris Yea209fde2020-07-22 13:54:51 -0700971 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700972 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500973 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800974 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500975 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700976 base::Result<std::unique_ptr<InputChannel>> channel =
977 dispatcher->createInputChannel(name);
978 token = (*channel)->getConnectionToken();
979 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800980 }
981
982 inputApplicationHandle->updateInfo();
983 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
984
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500985 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700986 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800987 mInfo.name = name;
chaviw3277faf2021-05-19 16:45:23 -0500988 mInfo.type = WindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500989 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000990 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800991 mInfo.frameLeft = 0;
992 mInfo.frameTop = 0;
993 mInfo.frameRight = WIDTH;
994 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700995 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800996 mInfo.globalScaleFactor = 1.0;
997 mInfo.touchableRegion.clear();
998 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
999 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -07001000 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -08001001 mInfo.hasWallpaper = false;
1002 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -08001003 mInfo.ownerPid = INJECTOR_PID;
1004 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -08001005 mInfo.displayId = displayId;
1006 }
1007
Arthur Hungabbb9d82021-09-01 14:52:30 +00001008 sp<FakeWindowHandle> clone(
1009 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001010 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001011 sp<FakeWindowHandle> handle =
1012 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1013 displayId, mInfo.token);
1014 return handle;
1015 }
1016
Vishnu Nair47074b82020-08-14 11:54:47 -07001017 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -08001018
Vishnu Nair958da932020-08-21 17:12:37 -07001019 void setVisible(bool visible) { mInfo.visible = visible; }
1020
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001021 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001022 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001023 }
1024
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001025 void setPaused(bool paused) { mInfo.paused = paused; }
1026
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001027 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1028
chaviw3277faf2021-05-19 16:45:23 -05001029 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001030
Bernardo Rufino7393d172021-02-26 13:56:11 +00001031 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1032
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001033 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001034 mInfo.frameLeft = frame.left;
1035 mInfo.frameTop = frame.top;
1036 mInfo.frameRight = frame.right;
1037 mInfo.frameBottom = frame.bottom;
1038 mInfo.touchableRegion.clear();
1039 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001040
1041 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1042 ui::Transform translate;
1043 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1044 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001045 }
1046
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001047 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1048
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001049 void setType(WindowInfo::Type type) { mInfo.type = type; }
1050
1051 void setHasWallpaper(bool hasWallpaper) { mInfo.hasWallpaper = hasWallpaper; }
1052
chaviw3277faf2021-05-19 16:45:23 -05001053 void addFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags |= flags; }
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00001054
chaviw3277faf2021-05-19 16:45:23 -05001055 void setFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -08001056
chaviw3277faf2021-05-19 16:45:23 -05001057 void setInputFeatures(WindowInfo::Feature features) { mInfo.inputFeatures = features; }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001058
chaviw9eaa22c2020-07-01 16:21:27 -07001059 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1060 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1061 }
1062
1063 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001064
yunho.shinf4a80b82020-11-16 21:13:57 +09001065 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1066
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001067 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1068 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1069 expectedFlags);
1070 }
1071
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001072 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1073 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1074 }
1075
Svet Ganov5d3bc372020-01-26 23:11:07 -08001076 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001077 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001078 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1079 expectedFlags);
1080 }
1081
1082 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001083 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001084 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1085 expectedFlags);
1086 }
1087
1088 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001089 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001090 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1091 }
1092
1093 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1094 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001095 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1096 expectedFlags);
1097 }
1098
Svet Ganov5d3bc372020-01-26 23:11:07 -08001099 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001100 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1101 int32_t expectedFlags = 0) {
1102 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1103 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001104 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1105 }
1106
1107 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001108 int32_t expectedFlags = 0) {
1109 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1110 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001111 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1112 }
1113
1114 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001115 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001116 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1117 expectedFlags);
1118 }
1119
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001120 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1121 int32_t expectedFlags = 0) {
1122 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1123 expectedFlags);
1124 }
1125
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001126 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1127 ASSERT_NE(mInputReceiver, nullptr)
1128 << "Cannot consume events from a window with no receiver";
1129 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1130 }
1131
Prabir Pradhan99987712020-11-10 18:43:05 -08001132 void consumeCaptureEvent(bool hasCapture) {
1133 ASSERT_NE(mInputReceiver, nullptr)
1134 << "Cannot consume events from a window with no receiver";
1135 mInputReceiver->consumeCaptureEvent(hasCapture);
1136 }
1137
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001138 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1139 std::optional<int32_t> expectedDisplayId,
1140 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001141 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1142 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1143 expectedFlags);
1144 }
1145
arthurhungb89ccb02020-12-30 16:19:01 +08001146 void consumeDragEvent(bool isExiting, float x, float y) {
1147 mInputReceiver->consumeDragEvent(isExiting, x, y);
1148 }
1149
Antonio Kantekf16f2832021-09-28 04:39:20 +00001150 void consumeTouchModeEvent(bool inTouchMode) {
1151 ASSERT_NE(mInputReceiver, nullptr)
1152 << "Cannot consume events from a window with no receiver";
1153 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1154 }
1155
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001156 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001157 if (mInputReceiver == nullptr) {
1158 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1159 return std::nullopt;
1160 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001161 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001162 }
1163
1164 void finishEvent(uint32_t sequenceNum) {
1165 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1166 mInputReceiver->finishEvent(sequenceNum);
1167 }
1168
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001169 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1170 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1171 mInputReceiver->sendTimeline(inputEventId, timeline);
1172 }
1173
chaviwaf87b3e2019-10-01 16:59:28 -07001174 InputEvent* consume() {
1175 if (mInputReceiver == nullptr) {
1176 return nullptr;
1177 }
1178 return mInputReceiver->consume();
1179 }
1180
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001181 MotionEvent* consumeMotion() {
1182 InputEvent* event = consume();
1183 if (event == nullptr) {
1184 ADD_FAILURE() << "Consume failed : no event";
1185 return nullptr;
1186 }
1187 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1188 ADD_FAILURE() << "Instead of motion event, got "
1189 << inputEventTypeToString(event->getType());
1190 return nullptr;
1191 }
1192 return static_cast<MotionEvent*>(event);
1193 }
1194
Arthur Hungb92218b2018-08-14 12:00:21 +08001195 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001196 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001197 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001198 return; // Can't receive events if the window does not have input channel
1199 }
1200 ASSERT_NE(nullptr, mInputReceiver)
1201 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001202 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001203 }
1204
chaviwaf87b3e2019-10-01 16:59:28 -07001205 sp<IBinder> getToken() { return mInfo.token; }
1206
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001207 const std::string& getName() { return mName; }
1208
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001209 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1210 mInfo.ownerPid = ownerPid;
1211 mInfo.ownerUid = ownerUid;
1212 }
1213
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001214 void destroyReceiver() { mInputReceiver = nullptr; }
1215
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001216 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1217
chaviwd1c23182019-12-20 18:44:56 -08001218private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001219 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001220 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001221 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001222};
1223
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001224std::atomic<int32_t> FakeWindowHandle::sId{1};
1225
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001226static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001227 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001228 int32_t displayId = ADISPLAY_ID_NONE,
1229 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001230 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1231 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001232 KeyEvent event;
1233 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1234
1235 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001236 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001237 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1238 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001239
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001240 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1241 if (!allowKeyRepeat) {
1242 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1243 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001244 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001245 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001246 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001247}
1248
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001249static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001250 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001251 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1252}
1253
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001254// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1255// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1256// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001257static InputEventInjectionResult injectKeyDownNoRepeat(
1258 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001259 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1260 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1261 /* allowKeyRepeat */ false);
1262}
1263
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001264static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001265 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001266 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1267}
1268
Garfield Tandf26e862020-07-01 20:18:19 -07001269class PointerBuilder {
1270public:
1271 PointerBuilder(int32_t id, int32_t toolType) {
1272 mProperties.clear();
1273 mProperties.id = id;
1274 mProperties.toolType = toolType;
1275 mCoords.clear();
1276 }
1277
1278 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1279
1280 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1281
1282 PointerBuilder& axis(int32_t axis, float value) {
1283 mCoords.setAxisValue(axis, value);
1284 return *this;
1285 }
1286
1287 PointerProperties buildProperties() const { return mProperties; }
1288
1289 PointerCoords buildCoords() const { return mCoords; }
1290
1291private:
1292 PointerProperties mProperties;
1293 PointerCoords mCoords;
1294};
1295
1296class MotionEventBuilder {
1297public:
1298 MotionEventBuilder(int32_t action, int32_t source) {
1299 mAction = action;
1300 mSource = source;
1301 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1302 }
1303
1304 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1305 mEventTime = eventTime;
1306 return *this;
1307 }
1308
1309 MotionEventBuilder& displayId(int32_t displayId) {
1310 mDisplayId = displayId;
1311 return *this;
1312 }
1313
1314 MotionEventBuilder& actionButton(int32_t actionButton) {
1315 mActionButton = actionButton;
1316 return *this;
1317 }
1318
arthurhung6d4bed92021-03-17 11:59:33 +08001319 MotionEventBuilder& buttonState(int32_t buttonState) {
1320 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001321 return *this;
1322 }
1323
1324 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1325 mRawXCursorPosition = rawXCursorPosition;
1326 return *this;
1327 }
1328
1329 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1330 mRawYCursorPosition = rawYCursorPosition;
1331 return *this;
1332 }
1333
1334 MotionEventBuilder& pointer(PointerBuilder pointer) {
1335 mPointers.push_back(pointer);
1336 return *this;
1337 }
1338
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001339 MotionEventBuilder& addFlag(uint32_t flags) {
1340 mFlags |= flags;
1341 return *this;
1342 }
1343
Garfield Tandf26e862020-07-01 20:18:19 -07001344 MotionEvent build() {
1345 std::vector<PointerProperties> pointerProperties;
1346 std::vector<PointerCoords> pointerCoords;
1347 for (const PointerBuilder& pointer : mPointers) {
1348 pointerProperties.push_back(pointer.buildProperties());
1349 pointerCoords.push_back(pointer.buildCoords());
1350 }
1351
1352 // Set mouse cursor position for the most common cases to avoid boilerplate.
1353 if (mSource == AINPUT_SOURCE_MOUSE &&
1354 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1355 mPointers.size() == 1) {
1356 mRawXCursorPosition = pointerCoords[0].getX();
1357 mRawYCursorPosition = pointerCoords[0].getY();
1358 }
1359
1360 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001361 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001362 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001363 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001364 mButtonState, MotionClassification::NONE, identityTransform,
1365 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001366 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1367 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001368
1369 return event;
1370 }
1371
1372private:
1373 int32_t mAction;
1374 int32_t mSource;
1375 nsecs_t mEventTime;
1376 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1377 int32_t mActionButton{0};
1378 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001379 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001380 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1381 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1382
1383 std::vector<PointerBuilder> mPointers;
1384};
1385
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001386static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001387 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001388 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001389 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001390 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1391 injectionTimeout,
1392 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1393}
1394
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001395static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001396 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001397 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001398 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001399 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1400 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001401 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001402 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001403 MotionEvent event = MotionEventBuilder(action, source)
1404 .displayId(displayId)
1405 .eventTime(eventTime)
1406 .rawXCursorPosition(cursorPosition.x)
1407 .rawYCursorPosition(cursorPosition.y)
1408 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1409 .x(position.x)
1410 .y(position.y))
1411 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001412
1413 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001414 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001415}
1416
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001417static InputEventInjectionResult injectMotionDown(
1418 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1419 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001420 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001421}
1422
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001423static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001424 int32_t source, int32_t displayId,
1425 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001426 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001427}
1428
Jackal Guof9696682018-10-05 12:23:23 +08001429static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1430 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1431 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001432 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1433 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1434 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001435
1436 return args;
1437}
1438
chaviwd1c23182019-12-20 18:44:56 -08001439static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1440 const std::vector<PointF>& points) {
1441 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001442 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1443 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1444 }
1445
chaviwd1c23182019-12-20 18:44:56 -08001446 PointerProperties pointerProperties[pointerCount];
1447 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001448
chaviwd1c23182019-12-20 18:44:56 -08001449 for (size_t i = 0; i < pointerCount; i++) {
1450 pointerProperties[i].clear();
1451 pointerProperties[i].id = i;
1452 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001453
chaviwd1c23182019-12-20 18:44:56 -08001454 pointerCoords[i].clear();
1455 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1456 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1457 }
Jackal Guof9696682018-10-05 12:23:23 +08001458
1459 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1460 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001461 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001462 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1463 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001464 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1465 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001466 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1467 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001468
1469 return args;
1470}
1471
chaviwd1c23182019-12-20 18:44:56 -08001472static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1473 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1474}
1475
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001476static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1477 const PointerCaptureRequest& request) {
1478 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001479}
1480
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001481/**
1482 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1483 * broken channel.
1484 */
1485TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1486 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1487 sp<FakeWindowHandle> window =
1488 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1489 ADISPLAY_ID_DEFAULT);
1490
1491 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1492
1493 // Window closes its channel, but the window remains.
1494 window->destroyReceiver();
1495 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1496}
1497
Arthur Hungb92218b2018-08-14 12:00:21 +08001498TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001499 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001500 sp<FakeWindowHandle> window =
1501 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001502
Arthur Hung72d8dc32020-03-28 00:48:39 +00001503 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001504 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1505 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1506 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001507
1508 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001509 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001510}
1511
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001512TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1513 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1514 sp<FakeWindowHandle> window =
1515 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1516
1517 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1518 // Inject a MotionEvent to an unknown display.
1519 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1520 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1521 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1522
1523 // Window should receive motion event.
1524 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1525}
1526
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001527/**
1528 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1529 * To ensure that window receives only events that were directly inside of it, add
1530 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1531 * when finding touched windows.
1532 * This test serves as a sanity check for the next test, where setInputWindows is
1533 * called twice.
1534 */
1535TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001536 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001537 sp<FakeWindowHandle> window =
1538 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1539 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001540 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001541
1542 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001543 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001544 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1545 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001546 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001547
1548 // Window should receive motion event.
1549 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1550}
1551
1552/**
1553 * Calling setInputWindows twice, with the same info, should not cause any issues.
1554 * To ensure that window receives only events that were directly inside of it, add
1555 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1556 * when finding touched windows.
1557 */
1558TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001559 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001560 sp<FakeWindowHandle> window =
1561 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1562 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001563 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001564
1565 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1566 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001567 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001568 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1569 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001570 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001571
1572 // Window should receive motion event.
1573 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1574}
1575
Arthur Hungb92218b2018-08-14 12:00:21 +08001576// The foreground window should receive the first touch down event.
1577TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001578 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001579 sp<FakeWindowHandle> windowTop =
1580 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1581 sp<FakeWindowHandle> windowSecond =
1582 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001583
Arthur Hung72d8dc32020-03-28 00:48:39 +00001584 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001585 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1586 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1587 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001588
1589 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001590 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001591 windowSecond->assertNoEvents();
1592}
1593
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001594/**
1595 * Two windows: A top window, and a wallpaper behind the window.
1596 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1597 * gets ACTION_CANCEL.
1598 * 1. foregroundWindow <-- has wallpaper (hasWallpaper=true)
1599 * 2. wallpaperWindow <-- is wallpaper (type=InputWindowInfo::Type::WALLPAPER)
1600 */
1601TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1602 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1603 sp<FakeWindowHandle> foregroundWindow =
1604 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1605 foregroundWindow->setHasWallpaper(true);
1606 sp<FakeWindowHandle> wallpaperWindow =
1607 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1608 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1609 constexpr int expectedWallpaperFlags =
1610 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1611
1612 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1613 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1614 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1615 {100, 200}))
1616 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1617
1618 // Both foreground window and its wallpaper should receive the touch down
1619 foregroundWindow->consumeMotionDown();
1620 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1621
1622 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1623 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1624 ADISPLAY_ID_DEFAULT, {110, 200}))
1625 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1626
1627 foregroundWindow->consumeMotionMove();
1628 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1629
1630 // Now the foreground window goes away, but the wallpaper stays
1631 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1632 foregroundWindow->consumeMotionCancel();
1633 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1634 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1635}
1636
1637/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001638 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1639 * with the following differences:
1640 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1641 * clean up the connection.
1642 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1643 * Ensure that there's no crash in the dispatcher.
1644 */
1645TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1646 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1647 sp<FakeWindowHandle> foregroundWindow =
1648 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1649 foregroundWindow->setHasWallpaper(true);
1650 sp<FakeWindowHandle> wallpaperWindow =
1651 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1652 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1653 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 // Wallpaper closes its channel, but the window remains.
1675 wallpaperWindow->destroyReceiver();
1676 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1677
1678 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1679 // is no longer valid.
1680 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1681 foregroundWindow->consumeMotionCancel();
1682}
1683
1684/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001685 * A single window that receives touch (on top), and a wallpaper window underneath it.
1686 * The top window gets a multitouch gesture.
1687 * Ensure that wallpaper gets the same gesture.
1688 */
1689TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1690 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1691 sp<FakeWindowHandle> window =
1692 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1693 window->setHasWallpaper(true);
1694
1695 sp<FakeWindowHandle> wallpaperWindow =
1696 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1697 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1698 constexpr int expectedWallpaperFlags =
1699 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1700
1701 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1702
1703 // Touch down on top window
1704 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1705 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1706 {100, 100}))
1707 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1708
1709 // Both top window and its wallpaper should receive the touch down
1710 window->consumeMotionDown();
1711 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1712
1713 // Second finger down on the top window
1714 const MotionEvent secondFingerDownEvent =
1715 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1716 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1717 AINPUT_SOURCE_TOUCHSCREEN)
1718 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1719 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1720 .x(100)
1721 .y(100))
1722 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1723 .x(150)
1724 .y(150))
1725 .build();
1726 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1727 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1728 InputEventInjectionSync::WAIT_FOR_RESULT))
1729 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1730
1731 window->consumeMotionPointerDown(1 /* pointerIndex */);
1732 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1733 expectedWallpaperFlags);
1734 window->assertNoEvents();
1735 wallpaperWindow->assertNoEvents();
1736}
1737
1738/**
1739 * Two windows: a window on the left and window on the right.
1740 * A third window, wallpaper, is behind both windows, and spans both top windows.
1741 * The first touch down goes to the left window. A second pointer touches down on the right window.
1742 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1743 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1744 * ACTION_POINTER_DOWN(1).
1745 */
1746TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1747 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1748 sp<FakeWindowHandle> leftWindow =
1749 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1750 leftWindow->setFrame(Rect(0, 0, 200, 200));
1751 leftWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1752 leftWindow->setHasWallpaper(true);
1753
1754 sp<FakeWindowHandle> rightWindow =
1755 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1756 rightWindow->setFrame(Rect(200, 0, 400, 200));
1757 rightWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1758 rightWindow->setHasWallpaper(true);
1759
1760 sp<FakeWindowHandle> wallpaperWindow =
1761 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1762 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
1763 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1764 constexpr int expectedWallpaperFlags =
1765 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1766
1767 mDispatcher->setInputWindows(
1768 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1769
1770 // Touch down on left window
1771 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1772 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1773 {100, 100}))
1774 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1775
1776 // Both foreground window and its wallpaper should receive the touch down
1777 leftWindow->consumeMotionDown();
1778 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1779
1780 // Second finger down on the right window
1781 const MotionEvent secondFingerDownEvent =
1782 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1783 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1784 AINPUT_SOURCE_TOUCHSCREEN)
1785 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1786 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1787 .x(100)
1788 .y(100))
1789 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1790 .x(300)
1791 .y(100))
1792 .build();
1793 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1794 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1795 InputEventInjectionSync::WAIT_FOR_RESULT))
1796 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1797
1798 leftWindow->consumeMotionMove();
1799 // Since the touch is split, right window gets ACTION_DOWN
1800 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1801 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1802 expectedWallpaperFlags);
1803
1804 // Now, leftWindow, which received the first finger, disappears.
1805 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1806 leftWindow->consumeMotionCancel();
1807 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1808 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1809
1810 // The pointer that's still down on the right window moves, and goes to the right window only.
1811 // As far as the dispatcher's concerned though, both pointers are still present.
1812 const MotionEvent secondFingerMoveEvent =
1813 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1814 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1815 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1816 .x(100)
1817 .y(100))
1818 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1819 .x(310)
1820 .y(110))
1821 .build();
1822 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1823 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1824 InputEventInjectionSync::WAIT_FOR_RESULT));
1825 rightWindow->consumeMotionMove();
1826
1827 leftWindow->assertNoEvents();
1828 rightWindow->assertNoEvents();
1829 wallpaperWindow->assertNoEvents();
1830}
1831
Garfield Tandf26e862020-07-01 20:18:19 -07001832TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001833 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001834 sp<FakeWindowHandle> windowLeft =
1835 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1836 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001837 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001838 sp<FakeWindowHandle> windowRight =
1839 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1840 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001841 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001842
1843 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1844
1845 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1846
1847 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001848 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001849 injectMotionEvent(mDispatcher,
1850 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1851 AINPUT_SOURCE_MOUSE)
1852 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1853 .x(900)
1854 .y(400))
1855 .build()));
1856 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1857 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1858 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1859 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1860
1861 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001862 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001863 injectMotionEvent(mDispatcher,
1864 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1865 AINPUT_SOURCE_MOUSE)
1866 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1867 .x(300)
1868 .y(400))
1869 .build()));
1870 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1871 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1872 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1873 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1874 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1875 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1876
1877 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001878 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001879 injectMotionEvent(mDispatcher,
1880 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1881 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1882 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1883 .x(300)
1884 .y(400))
1885 .build()));
1886 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1887
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001888 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001889 injectMotionEvent(mDispatcher,
1890 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1891 AINPUT_SOURCE_MOUSE)
1892 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1893 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1894 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1895 .x(300)
1896 .y(400))
1897 .build()));
1898 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1899 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1900
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001901 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001902 injectMotionEvent(mDispatcher,
1903 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1904 AINPUT_SOURCE_MOUSE)
1905 .buttonState(0)
1906 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1907 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1908 .x(300)
1909 .y(400))
1910 .build()));
1911 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1912 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1913
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001914 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001915 injectMotionEvent(mDispatcher,
1916 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1917 .buttonState(0)
1918 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1919 .x(300)
1920 .y(400))
1921 .build()));
1922 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1923
1924 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001925 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001926 injectMotionEvent(mDispatcher,
1927 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1928 AINPUT_SOURCE_MOUSE)
1929 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1930 .x(900)
1931 .y(400))
1932 .build()));
1933 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1934 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1935 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1936 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1937 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1938 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1939}
1940
1941// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1942// directly in this test.
1943TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001944 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001945 sp<FakeWindowHandle> window =
1946 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1947 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001948 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001949
1950 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1951
1952 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1953
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001954 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001955 injectMotionEvent(mDispatcher,
1956 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1957 AINPUT_SOURCE_MOUSE)
1958 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1959 .x(300)
1960 .y(400))
1961 .build()));
1962 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1963 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1964
1965 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001966 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001967 injectMotionEvent(mDispatcher,
1968 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1969 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1970 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1971 .x(300)
1972 .y(400))
1973 .build()));
1974 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1975
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001976 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001977 injectMotionEvent(mDispatcher,
1978 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1979 AINPUT_SOURCE_MOUSE)
1980 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1981 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1982 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1983 .x(300)
1984 .y(400))
1985 .build()));
1986 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1987 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1988
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001989 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001990 injectMotionEvent(mDispatcher,
1991 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1992 AINPUT_SOURCE_MOUSE)
1993 .buttonState(0)
1994 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1995 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1996 .x(300)
1997 .y(400))
1998 .build()));
1999 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2000 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2001
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002002 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002003 injectMotionEvent(mDispatcher,
2004 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2005 .buttonState(0)
2006 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2007 .x(300)
2008 .y(400))
2009 .build()));
2010 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2011
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002012 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002013 injectMotionEvent(mDispatcher,
2014 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2015 AINPUT_SOURCE_MOUSE)
2016 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2017 .x(300)
2018 .y(400))
2019 .build()));
2020 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2021 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2022}
2023
Garfield Tan00f511d2019-06-12 16:55:40 -07002024TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002025 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002026
2027 sp<FakeWindowHandle> windowLeft =
2028 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2029 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002030 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002031 sp<FakeWindowHandle> windowRight =
2032 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2033 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05002034 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002035
2036 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2037
Arthur Hung72d8dc32020-03-28 00:48:39 +00002038 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002039
2040 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2041 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002042 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002043 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002044 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002045 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002046 windowRight->assertNoEvents();
2047}
2048
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002049TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002050 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002051 sp<FakeWindowHandle> window =
2052 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002053 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002054
Arthur Hung72d8dc32020-03-28 00:48:39 +00002055 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002056 setFocusedWindow(window);
2057
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002058 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002059
2060 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2061 mDispatcher->notifyKey(&keyArgs);
2062
2063 // Window should receive key down event.
2064 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2065
2066 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2067 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002068 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002069 mDispatcher->notifyDeviceReset(&args);
2070 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2071 AKEY_EVENT_FLAG_CANCELED);
2072}
2073
2074TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002075 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002076 sp<FakeWindowHandle> window =
2077 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2078
Arthur Hung72d8dc32020-03-28 00:48:39 +00002079 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002080
2081 NotifyMotionArgs motionArgs =
2082 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2083 ADISPLAY_ID_DEFAULT);
2084 mDispatcher->notifyMotion(&motionArgs);
2085
2086 // Window should receive motion down event.
2087 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2088
2089 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2090 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002091 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002092 mDispatcher->notifyDeviceReset(&args);
2093 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2094 0 /*expectedFlags*/);
2095}
2096
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002097/**
2098 * Ensure the correct coordinate spaces are used by InputDispatcher.
2099 *
2100 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2101 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2102 * space.
2103 */
2104class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2105public:
2106 void SetUp() override {
2107 InputDispatcherTest::SetUp();
2108 mDisplayInfos.clear();
2109 mWindowInfos.clear();
2110 }
2111
2112 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2113 gui::DisplayInfo info;
2114 info.displayId = displayId;
2115 info.transform = transform;
2116 mDisplayInfos.push_back(std::move(info));
2117 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2118 }
2119
2120 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2121 mWindowInfos.push_back(*windowHandle->getInfo());
2122 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2123 }
2124
2125 // Set up a test scenario where the display has a scaled projection and there are two windows
2126 // on the display.
2127 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2128 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2129 // respectively.
2130 ui::Transform displayTransform;
2131 displayTransform.set(2, 0, 0, 4);
2132 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2133
2134 std::shared_ptr<FakeApplicationHandle> application =
2135 std::make_shared<FakeApplicationHandle>();
2136
2137 // Add two windows to the display. Their frames are represented in the display space.
2138 sp<FakeWindowHandle> firstWindow =
2139 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2140 firstWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2141 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2142 addWindow(firstWindow);
2143
2144 sp<FakeWindowHandle> secondWindow =
2145 new FakeWindowHandle(application, mDispatcher, "Second Window",
2146 ADISPLAY_ID_DEFAULT);
2147 secondWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2148 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2149 addWindow(secondWindow);
2150 return {std::move(firstWindow), std::move(secondWindow)};
2151 }
2152
2153private:
2154 std::vector<gui::DisplayInfo> mDisplayInfos;
2155 std::vector<gui::WindowInfo> mWindowInfos;
2156};
2157
2158TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2159 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2160 // Send down to the first window. The point is represented in the display space. The point is
2161 // selected so that if the hit test was done with the transform applied to it, then it would
2162 // end up in the incorrect window.
2163 NotifyMotionArgs downMotionArgs =
2164 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2165 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2166 mDispatcher->notifyMotion(&downMotionArgs);
2167
2168 firstWindow->consumeMotionDown();
2169 secondWindow->assertNoEvents();
2170}
2171
2172// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2173// the event should be treated as being in the logical display space.
2174TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2175 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2176 // Send down to the first window. The point is represented in the logical display space. The
2177 // point is selected so that if the hit test was done in logical display space, then it would
2178 // end up in the incorrect window.
2179 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2180 PointF{75 * 2, 55 * 4});
2181
2182 firstWindow->consumeMotionDown();
2183 secondWindow->assertNoEvents();
2184}
2185
2186TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2187 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2188
2189 // Send down to the second window.
2190 NotifyMotionArgs downMotionArgs =
2191 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2192 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2193 mDispatcher->notifyMotion(&downMotionArgs);
2194
2195 firstWindow->assertNoEvents();
2196 const MotionEvent* event = secondWindow->consumeMotion();
2197 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2198
2199 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2200 EXPECT_EQ(300, event->getRawX(0));
2201 EXPECT_EQ(880, event->getRawY(0));
2202
2203 // Ensure that the x and y values are in the window's coordinate space.
2204 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2205 // the logical display space. This will be the origin of the window space.
2206 EXPECT_EQ(100, event->getX(0));
2207 EXPECT_EQ(80, event->getY(0));
2208}
2209
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002210using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2211 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002212
2213class TransferTouchFixture : public InputDispatcherTest,
2214 public ::testing::WithParamInterface<TransferFunction> {};
2215
2216TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002217 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002218
2219 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002220 sp<FakeWindowHandle> firstWindow =
2221 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2222 sp<FakeWindowHandle> secondWindow =
2223 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002224
2225 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002226 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002227
2228 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002229 NotifyMotionArgs downMotionArgs =
2230 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2231 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002232 mDispatcher->notifyMotion(&downMotionArgs);
2233 // Only the first window should get the down event
2234 firstWindow->consumeMotionDown();
2235 secondWindow->assertNoEvents();
2236
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002237 // Transfer touch to the second window
2238 TransferFunction f = GetParam();
2239 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2240 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002241 // The first window gets cancel and the second gets down
2242 firstWindow->consumeMotionCancel();
2243 secondWindow->consumeMotionDown();
2244
2245 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002246 NotifyMotionArgs upMotionArgs =
2247 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2248 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002249 mDispatcher->notifyMotion(&upMotionArgs);
2250 // The first window gets no events and the second gets up
2251 firstWindow->assertNoEvents();
2252 secondWindow->consumeMotionUp();
2253}
2254
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002255TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002256 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002257
2258 PointF touchPoint = {10, 10};
2259
2260 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002261 sp<FakeWindowHandle> firstWindow =
2262 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2263 sp<FakeWindowHandle> secondWindow =
2264 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002265
2266 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002267 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002268
2269 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002270 NotifyMotionArgs downMotionArgs =
2271 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2272 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002273 mDispatcher->notifyMotion(&downMotionArgs);
2274 // Only the first window should get the down event
2275 firstWindow->consumeMotionDown();
2276 secondWindow->assertNoEvents();
2277
2278 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002279 NotifyMotionArgs pointerDownMotionArgs =
2280 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2281 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2282 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2283 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002284 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2285 // Only the first window should get the pointer down event
2286 firstWindow->consumeMotionPointerDown(1);
2287 secondWindow->assertNoEvents();
2288
2289 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002290 TransferFunction f = GetParam();
2291 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2292 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002293 // The first window gets cancel and the second gets down and pointer down
2294 firstWindow->consumeMotionCancel();
2295 secondWindow->consumeMotionDown();
2296 secondWindow->consumeMotionPointerDown(1);
2297
2298 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002299 NotifyMotionArgs pointerUpMotionArgs =
2300 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2301 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2302 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2303 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002304 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2305 // The first window gets nothing and the second gets pointer up
2306 firstWindow->assertNoEvents();
2307 secondWindow->consumeMotionPointerUp(1);
2308
2309 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002310 NotifyMotionArgs upMotionArgs =
2311 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2312 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002313 mDispatcher->notifyMotion(&upMotionArgs);
2314 // The first window gets nothing and the second gets up
2315 firstWindow->assertNoEvents();
2316 secondWindow->consumeMotionUp();
2317}
2318
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002319// For the cases of single pointer touch and two pointers non-split touch, the api's
2320// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2321// for the case where there are multiple pointers split across several windows.
2322INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2323 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002324 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2325 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002326 return dispatcher->transferTouch(destChannelToken);
2327 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002328 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2329 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002330 return dispatcher->transferTouchFocus(from, to,
2331 false /*isDragAndDrop*/);
2332 }));
2333
Svet Ganov5d3bc372020-01-26 23:11:07 -08002334TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002335 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002336
2337 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002338 sp<FakeWindowHandle> firstWindow =
2339 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002340 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002341 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002342
2343 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002344 sp<FakeWindowHandle> secondWindow =
2345 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002346 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002347 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002348
2349 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002350 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002351
2352 PointF pointInFirst = {300, 200};
2353 PointF pointInSecond = {300, 600};
2354
2355 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002356 NotifyMotionArgs firstDownMotionArgs =
2357 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2358 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002359 mDispatcher->notifyMotion(&firstDownMotionArgs);
2360 // Only the first window should get the down event
2361 firstWindow->consumeMotionDown();
2362 secondWindow->assertNoEvents();
2363
2364 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002365 NotifyMotionArgs secondDownMotionArgs =
2366 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2367 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2368 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2369 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002370 mDispatcher->notifyMotion(&secondDownMotionArgs);
2371 // The first window gets a move and the second a down
2372 firstWindow->consumeMotionMove();
2373 secondWindow->consumeMotionDown();
2374
2375 // Transfer touch focus to the second window
2376 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2377 // The first window gets cancel and the new gets pointer down (it already saw down)
2378 firstWindow->consumeMotionCancel();
2379 secondWindow->consumeMotionPointerDown(1);
2380
2381 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002382 NotifyMotionArgs pointerUpMotionArgs =
2383 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2384 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2385 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2386 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002387 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2388 // The first window gets nothing and the second gets pointer up
2389 firstWindow->assertNoEvents();
2390 secondWindow->consumeMotionPointerUp(1);
2391
2392 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002393 NotifyMotionArgs upMotionArgs =
2394 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2395 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002396 mDispatcher->notifyMotion(&upMotionArgs);
2397 // The first window gets nothing and the second gets up
2398 firstWindow->assertNoEvents();
2399 secondWindow->consumeMotionUp();
2400}
2401
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002402// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2403// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2404// touch is not supported, so the touch should continue on those windows and the transferred-to
2405// window should get nothing.
2406TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2407 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2408
2409 // Create a non touch modal window that supports split touch
2410 sp<FakeWindowHandle> firstWindow =
2411 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2412 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002413 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002414
2415 // Create a non touch modal window that supports split touch
2416 sp<FakeWindowHandle> secondWindow =
2417 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2418 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002419 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002420
2421 // Add the windows to the dispatcher
2422 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2423
2424 PointF pointInFirst = {300, 200};
2425 PointF pointInSecond = {300, 600};
2426
2427 // Send down to the first window
2428 NotifyMotionArgs firstDownMotionArgs =
2429 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2430 ADISPLAY_ID_DEFAULT, {pointInFirst});
2431 mDispatcher->notifyMotion(&firstDownMotionArgs);
2432 // Only the first window should get the down event
2433 firstWindow->consumeMotionDown();
2434 secondWindow->assertNoEvents();
2435
2436 // Send down to the second window
2437 NotifyMotionArgs secondDownMotionArgs =
2438 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2439 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2440 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2441 {pointInFirst, pointInSecond});
2442 mDispatcher->notifyMotion(&secondDownMotionArgs);
2443 // The first window gets a move and the second a down
2444 firstWindow->consumeMotionMove();
2445 secondWindow->consumeMotionDown();
2446
2447 // Transfer touch focus to the second window
2448 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2449 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2450 ASSERT_FALSE(transferred);
2451 firstWindow->assertNoEvents();
2452 secondWindow->assertNoEvents();
2453
2454 // The rest of the dispatch should proceed as normal
2455 // Send pointer up to the second window
2456 NotifyMotionArgs pointerUpMotionArgs =
2457 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2458 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2459 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2460 {pointInFirst, pointInSecond});
2461 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2462 // The first window gets MOVE and the second gets pointer up
2463 firstWindow->consumeMotionMove();
2464 secondWindow->consumeMotionUp();
2465
2466 // Send up event to the first window
2467 NotifyMotionArgs upMotionArgs =
2468 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2469 ADISPLAY_ID_DEFAULT);
2470 mDispatcher->notifyMotion(&upMotionArgs);
2471 // The first window gets nothing and the second gets up
2472 firstWindow->consumeMotionUp();
2473 secondWindow->assertNoEvents();
2474}
2475
Arthur Hungabbb9d82021-09-01 14:52:30 +00002476// This case will create two windows and one mirrored window on the default display and mirror
2477// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2478// the windows info of second display before default display.
2479TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2480 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2481 sp<FakeWindowHandle> firstWindowInPrimary =
2482 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2483 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2484 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2485 sp<FakeWindowHandle> secondWindowInPrimary =
2486 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2487 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2488 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2489
2490 sp<FakeWindowHandle> mirrorWindowInPrimary =
2491 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2492 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2493 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2494
2495 sp<FakeWindowHandle> firstWindowInSecondary =
2496 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2497 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2498 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2499
2500 sp<FakeWindowHandle> secondWindowInSecondary =
2501 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2502 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2503 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2504
2505 // Update window info, let it find window handle of second display first.
2506 mDispatcher->setInputWindows(
2507 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2508 {ADISPLAY_ID_DEFAULT,
2509 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2510
2511 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2512 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2513 {50, 50}))
2514 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2515
2516 // Window should receive motion event.
2517 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2518
2519 // Transfer touch focus
2520 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2521 secondWindowInPrimary->getToken()));
2522 // The first window gets cancel.
2523 firstWindowInPrimary->consumeMotionCancel();
2524 secondWindowInPrimary->consumeMotionDown();
2525
2526 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2527 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2528 ADISPLAY_ID_DEFAULT, {150, 50}))
2529 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2530 firstWindowInPrimary->assertNoEvents();
2531 secondWindowInPrimary->consumeMotionMove();
2532
2533 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2534 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2535 {150, 50}))
2536 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2537 firstWindowInPrimary->assertNoEvents();
2538 secondWindowInPrimary->consumeMotionUp();
2539}
2540
2541// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2542// 'transferTouch' api.
2543TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2544 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2545 sp<FakeWindowHandle> firstWindowInPrimary =
2546 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2547 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2548 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2549 sp<FakeWindowHandle> secondWindowInPrimary =
2550 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2551 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2552 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2553
2554 sp<FakeWindowHandle> mirrorWindowInPrimary =
2555 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2556 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2557 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2558
2559 sp<FakeWindowHandle> firstWindowInSecondary =
2560 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2561 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2562 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2563
2564 sp<FakeWindowHandle> secondWindowInSecondary =
2565 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2566 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2567 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2568
2569 // Update window info, let it find window handle of second display first.
2570 mDispatcher->setInputWindows(
2571 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2572 {ADISPLAY_ID_DEFAULT,
2573 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2574
2575 // Touch on second display.
2576 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2577 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2578 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2579
2580 // Window should receive motion event.
2581 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2582
2583 // Transfer touch focus
2584 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2585
2586 // The first window gets cancel.
2587 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2588 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2589
2590 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2591 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2592 SECOND_DISPLAY_ID, {150, 50}))
2593 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2594 firstWindowInPrimary->assertNoEvents();
2595 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2596
2597 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2598 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2599 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2600 firstWindowInPrimary->assertNoEvents();
2601 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2602}
2603
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002604TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002605 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002606 sp<FakeWindowHandle> window =
2607 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2608
Vishnu Nair47074b82020-08-14 11:54:47 -07002609 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002610 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002611 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002612
2613 window->consumeFocusEvent(true);
2614
2615 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2616 mDispatcher->notifyKey(&keyArgs);
2617
2618 // Window should receive key down event.
2619 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2620}
2621
2622TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002623 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002624 sp<FakeWindowHandle> window =
2625 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2626
Arthur Hung72d8dc32020-03-28 00:48:39 +00002627 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002628
2629 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2630 mDispatcher->notifyKey(&keyArgs);
2631 mDispatcher->waitForIdle();
2632
2633 window->assertNoEvents();
2634}
2635
2636// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2637TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002638 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002639 sp<FakeWindowHandle> window =
2640 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2641
Arthur Hung72d8dc32020-03-28 00:48:39 +00002642 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002643
2644 // Send key
2645 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2646 mDispatcher->notifyKey(&keyArgs);
2647 // Send motion
2648 NotifyMotionArgs motionArgs =
2649 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2650 ADISPLAY_ID_DEFAULT);
2651 mDispatcher->notifyMotion(&motionArgs);
2652
2653 // Window should receive only the motion event
2654 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2655 window->assertNoEvents(); // Key event or focus event will not be received
2656}
2657
arthurhungea3f4fc2020-12-21 23:18:53 +08002658TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2659 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2660
2661 // Create first non touch modal window that supports split touch
2662 sp<FakeWindowHandle> firstWindow =
2663 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2664 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002665 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002666
2667 // Create second non touch modal window that supports split touch
2668 sp<FakeWindowHandle> secondWindow =
2669 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2670 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002671 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002672
2673 // Add the windows to the dispatcher
2674 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2675
2676 PointF pointInFirst = {300, 200};
2677 PointF pointInSecond = {300, 600};
2678
2679 // Send down to the first window
2680 NotifyMotionArgs firstDownMotionArgs =
2681 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2682 ADISPLAY_ID_DEFAULT, {pointInFirst});
2683 mDispatcher->notifyMotion(&firstDownMotionArgs);
2684 // Only the first window should get the down event
2685 firstWindow->consumeMotionDown();
2686 secondWindow->assertNoEvents();
2687
2688 // Send down to the second window
2689 NotifyMotionArgs secondDownMotionArgs =
2690 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2691 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2692 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2693 {pointInFirst, pointInSecond});
2694 mDispatcher->notifyMotion(&secondDownMotionArgs);
2695 // The first window gets a move and the second a down
2696 firstWindow->consumeMotionMove();
2697 secondWindow->consumeMotionDown();
2698
2699 // Send pointer cancel to the second window
2700 NotifyMotionArgs pointerUpMotionArgs =
2701 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2702 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2703 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2704 {pointInFirst, pointInSecond});
2705 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2706 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2707 // The first window gets move and the second gets cancel.
2708 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2709 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2710
2711 // Send up event.
2712 NotifyMotionArgs upMotionArgs =
2713 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2714 ADISPLAY_ID_DEFAULT);
2715 mDispatcher->notifyMotion(&upMotionArgs);
2716 // The first window gets up and the second gets nothing.
2717 firstWindow->consumeMotionUp();
2718 secondWindow->assertNoEvents();
2719}
2720
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002721TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2722 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2723
2724 sp<FakeWindowHandle> window =
2725 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2726 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2727 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2728 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2729 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2730
2731 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2732 window->assertNoEvents();
2733 mDispatcher->waitForIdle();
2734}
2735
chaviwd1c23182019-12-20 18:44:56 -08002736class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002737public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002738 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002739 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002740 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002741 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002742 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002743 }
2744
chaviwd1c23182019-12-20 18:44:56 -08002745 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2746
2747 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2748 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2749 expectedDisplayId, expectedFlags);
2750 }
2751
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002752 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2753
2754 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2755
chaviwd1c23182019-12-20 18:44:56 -08002756 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2757 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2758 expectedDisplayId, expectedFlags);
2759 }
2760
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002761 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2762 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2763 expectedDisplayId, expectedFlags);
2764 }
2765
chaviwd1c23182019-12-20 18:44:56 -08002766 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2767 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2768 expectedDisplayId, expectedFlags);
2769 }
2770
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002771 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2772 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2773 expectedDisplayId, expectedFlags);
2774 }
2775
Arthur Hungfbfa5722021-11-16 02:45:54 +00002776 void consumeMotionPointerDown(int32_t pointerIdx) {
2777 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2778 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2779 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2780 0 /*expectedFlags*/);
2781 }
2782
Evan Rosky84f07f02021-04-16 10:42:42 -07002783 MotionEvent* consumeMotion() {
2784 InputEvent* event = mInputReceiver->consume();
2785 if (!event) {
2786 ADD_FAILURE() << "No event was produced";
2787 return nullptr;
2788 }
2789 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2790 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2791 return nullptr;
2792 }
2793 return static_cast<MotionEvent*>(event);
2794 }
2795
chaviwd1c23182019-12-20 18:44:56 -08002796 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2797
2798private:
2799 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002800};
2801
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002802/**
2803 * Two entities that receive touch: A window, and a global monitor.
2804 * The touch goes to the window, and then the window disappears.
2805 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2806 * for the monitor, as well.
2807 * 1. foregroundWindow
2808 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2809 */
2810TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_GlobalMonitorTouchIsCanceled) {
2811 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2812 sp<FakeWindowHandle> window =
2813 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2814
2815 FakeMonitorReceiver monitor =
2816 FakeMonitorReceiver(mDispatcher, "GlobalMonitor", ADISPLAY_ID_DEFAULT,
2817 false /*isGestureMonitor*/);
2818
2819 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2820 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2821 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2822 {100, 200}))
2823 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2824
2825 // Both the foreground window and the global monitor should receive the touch down
2826 window->consumeMotionDown();
2827 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2828
2829 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2830 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2831 ADISPLAY_ID_DEFAULT, {110, 200}))
2832 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2833
2834 window->consumeMotionMove();
2835 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2836
2837 // Now the foreground window goes away
2838 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2839 window->consumeMotionCancel();
2840 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2841
2842 // If more events come in, there will be no more foreground window to send them to. This will
2843 // cause a cancel for the monitor, as well.
2844 ASSERT_EQ(InputEventInjectionResult::FAILED,
2845 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2846 ADISPLAY_ID_DEFAULT, {120, 200}))
2847 << "Injection should fail because the window was removed";
2848 window->assertNoEvents();
2849 // Global monitor now gets the cancel
2850 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2851}
2852
Michael Wright3a240c42019-12-10 20:53:41 +00002853// Tests for gesture monitors
2854TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002855 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002856 sp<FakeWindowHandle> window =
2857 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002858 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002859
chaviwd1c23182019-12-20 18:44:56 -08002860 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2861 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002862
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002863 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002864 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002865 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002866 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002867 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002868}
2869
2870TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002871 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002872 sp<FakeWindowHandle> window =
2873 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2874
2875 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002876 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002877
Arthur Hung72d8dc32020-03-28 00:48:39 +00002878 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002879 setFocusedWindow(window);
2880
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002881 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002882
chaviwd1c23182019-12-20 18:44:56 -08002883 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2884 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002885
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002886 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2887 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002888 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002889 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002890}
2891
2892TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002893 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002894 sp<FakeWindowHandle> window =
2895 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002896 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002897
chaviwd1c23182019-12-20 18:44:56 -08002898 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2899 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002900
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002901 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002902 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002903 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002904 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002905 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002906
2907 window->releaseChannel();
2908
chaviwd1c23182019-12-20 18:44:56 -08002909 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002910
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002911 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002912 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002913 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002914 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002915}
2916
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002917TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2918 FakeMonitorReceiver monitor =
2919 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2920 true /*isGestureMonitor*/);
2921
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002922 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002923 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2924 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2925 ASSERT_TRUE(consumeSeq);
2926
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002927 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002928 monitor.finishEvent(*consumeSeq);
2929 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002930 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002931}
2932
Evan Rosky84f07f02021-04-16 10:42:42 -07002933// Tests for gesture monitors
2934TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2935 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2936 sp<FakeWindowHandle> window =
2937 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2938 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2939 window->setWindowOffset(20, 40);
2940 window->setWindowTransform(0, 1, -1, 0);
2941
2942 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2943 true /*isGestureMonitor*/);
2944
2945 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2946 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2947 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2948 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2949 MotionEvent* event = monitor.consumeMotion();
2950 // Even though window has transform, gesture monitor must not.
2951 ASSERT_EQ(ui::Transform(), event->getTransform());
2952}
2953
Arthur Hungb3307ee2021-10-14 10:57:37 +00002954TEST_F(InputDispatcherTest, GestureMonitor_NoWindow) {
2955 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2956 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2957 true /*isGestureMonitor*/);
2958
2959 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2960 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2961 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2962 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2963}
2964
chaviw81e2bb92019-12-18 15:03:51 -08002965TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002966 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002967 sp<FakeWindowHandle> window =
2968 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2969
Arthur Hung72d8dc32020-03-28 00:48:39 +00002970 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002971
2972 NotifyMotionArgs motionArgs =
2973 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2974 ADISPLAY_ID_DEFAULT);
2975
2976 mDispatcher->notifyMotion(&motionArgs);
2977 // Window should receive motion down event.
2978 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2979
2980 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002981 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002982 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2983 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2984 motionArgs.pointerCoords[0].getX() - 10);
2985
2986 mDispatcher->notifyMotion(&motionArgs);
2987 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2988 0 /*expectedFlags*/);
2989}
2990
Arthur Hungfbfa5722021-11-16 02:45:54 +00002991TEST_F(InputDispatcherTest, GestureMonitor_SplitIfNoWindowTouched) {
2992 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2993 true /*isGestureMonitor*/);
2994
2995 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2996 // Create a non touch modal window that supports split touch
2997 sp<FakeWindowHandle> window =
2998 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2999 window->setFrame(Rect(0, 0, 100, 100));
3000 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
3001 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3002
3003 // First finger down, no window touched.
3004 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3005 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3006 {100, 200}))
3007 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3008 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3009 window->assertNoEvents();
3010
3011 // Second finger down on window, the window should receive touch down.
3012 const MotionEvent secondFingerDownEvent =
3013 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
3014 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
3015 AINPUT_SOURCE_TOUCHSCREEN)
3016 .displayId(ADISPLAY_ID_DEFAULT)
3017 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3018 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3019 .x(100)
3020 .y(200))
3021 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3022 .build();
3023 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3024 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
3025 InputEventInjectionSync::WAIT_FOR_RESULT))
3026 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3027
3028 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3029 monitor.consumeMotionPointerDown(1 /* pointerIndex */);
3030}
3031
3032TEST_F(InputDispatcherTest, GestureMonitor_NoSplitAfterPilfer) {
3033 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
3034 true /*isGestureMonitor*/);
3035
3036 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3037 // Create a non touch modal window that supports split touch
3038 sp<FakeWindowHandle> window =
3039 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3040 window->setFrame(Rect(0, 0, 100, 100));
3041 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
3042 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3043
3044 // First finger down, no window touched.
3045 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3046 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3047 {100, 200}))
3048 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3049 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3050 window->assertNoEvents();
3051
3052 // Gesture monitor pilfer the pointers.
3053 mDispatcher->pilferPointers(monitor.getToken());
3054
3055 // Second finger down on window, the window should not receive touch down.
3056 const MotionEvent secondFingerDownEvent =
3057 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
3058 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
3059 AINPUT_SOURCE_TOUCHSCREEN)
3060 .displayId(ADISPLAY_ID_DEFAULT)
3061 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3062 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3063 .x(100)
3064 .y(200))
3065 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3066 .build();
3067 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3068 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
3069 InputEventInjectionSync::WAIT_FOR_RESULT))
3070 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3071
3072 window->assertNoEvents();
3073 monitor.consumeMotionPointerDown(1 /* pointerIndex */);
3074}
3075
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003076/**
3077 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3078 * the device default right away. In the test scenario, we check both the default value,
3079 * and the action of enabling / disabling.
3080 */
3081TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003082 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003083 sp<FakeWindowHandle> window =
3084 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3085
3086 // Set focused application.
3087 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003088 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003089
3090 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003091 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003092 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003093 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3094
3095 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003096 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003097 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003098 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3099
3100 SCOPED_TRACE("Disable touch mode");
3101 mDispatcher->setInTouchMode(false);
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");
3114 mDispatcher->setInTouchMode(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003115 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003116 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003117 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003118 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003119 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3120
3121 window->assertNoEvents();
3122}
3123
Gang Wange9087892020-01-07 12:17:14 -05003124TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003125 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003126 sp<FakeWindowHandle> window =
3127 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3128
3129 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003130 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003131
Arthur Hung72d8dc32020-03-28 00:48:39 +00003132 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003133 setFocusedWindow(window);
3134
Gang Wange9087892020-01-07 12:17:14 -05003135 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3136
3137 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3138 mDispatcher->notifyKey(&keyArgs);
3139
3140 InputEvent* event = window->consume();
3141 ASSERT_NE(event, nullptr);
3142
3143 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3144 ASSERT_NE(verified, nullptr);
3145 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3146
3147 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3148 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3149 ASSERT_EQ(keyArgs.source, verified->source);
3150 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3151
3152 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3153
3154 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003155 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003156 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003157 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3158 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3159 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3160 ASSERT_EQ(0, verifiedKey.repeatCount);
3161}
3162
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003163TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003164 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003165 sp<FakeWindowHandle> window =
3166 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3167
3168 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3169
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003170 ui::Transform transform;
3171 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3172
3173 gui::DisplayInfo displayInfo;
3174 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3175 displayInfo.transform = transform;
3176
3177 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003178
3179 NotifyMotionArgs motionArgs =
3180 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3181 ADISPLAY_ID_DEFAULT);
3182 mDispatcher->notifyMotion(&motionArgs);
3183
3184 InputEvent* event = window->consume();
3185 ASSERT_NE(event, nullptr);
3186
3187 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3188 ASSERT_NE(verified, nullptr);
3189 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3190
3191 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3192 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3193 EXPECT_EQ(motionArgs.source, verified->source);
3194 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3195
3196 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3197
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003198 const vec2 rawXY =
3199 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3200 motionArgs.pointerCoords[0].getXYValue());
3201 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3202 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003203 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003204 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003205 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003206 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3207 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3208}
3209
chaviw09c8d2d2020-08-24 15:48:26 -07003210/**
3211 * Ensure that separate calls to sign the same data are generating the same key.
3212 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3213 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3214 * tests.
3215 */
3216TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3217 KeyEvent event = getTestKeyEvent();
3218 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3219
3220 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3221 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3222 ASSERT_EQ(hmac1, hmac2);
3223}
3224
3225/**
3226 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3227 */
3228TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3229 KeyEvent event = getTestKeyEvent();
3230 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3231 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3232
3233 verifiedEvent.deviceId += 1;
3234 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3235
3236 verifiedEvent.source += 1;
3237 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3238
3239 verifiedEvent.eventTimeNanos += 1;
3240 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3241
3242 verifiedEvent.displayId += 1;
3243 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3244
3245 verifiedEvent.action += 1;
3246 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3247
3248 verifiedEvent.downTimeNanos += 1;
3249 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3250
3251 verifiedEvent.flags += 1;
3252 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3253
3254 verifiedEvent.keyCode += 1;
3255 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3256
3257 verifiedEvent.scanCode += 1;
3258 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3259
3260 verifiedEvent.metaState += 1;
3261 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3262
3263 verifiedEvent.repeatCount += 1;
3264 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3265}
3266
Vishnu Nair958da932020-08-21 17:12:37 -07003267TEST_F(InputDispatcherTest, SetFocusedWindow) {
3268 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3269 sp<FakeWindowHandle> windowTop =
3270 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3271 sp<FakeWindowHandle> windowSecond =
3272 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3273 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3274
3275 // Top window is also focusable but is not granted focus.
3276 windowTop->setFocusable(true);
3277 windowSecond->setFocusable(true);
3278 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3279 setFocusedWindow(windowSecond);
3280
3281 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003282 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3283 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003284
3285 // Focused window should receive event.
3286 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3287 windowTop->assertNoEvents();
3288}
3289
3290TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3291 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3292 sp<FakeWindowHandle> window =
3293 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3294 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3295
3296 window->setFocusable(true);
3297 // Release channel for window is no longer valid.
3298 window->releaseChannel();
3299 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3300 setFocusedWindow(window);
3301
3302 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003303 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3304 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003305
3306 // window channel is invalid, so it should not receive any input event.
3307 window->assertNoEvents();
3308}
3309
3310TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3311 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3312 sp<FakeWindowHandle> window =
3313 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3314 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3315
3316 // Window is not focusable.
3317 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3318 setFocusedWindow(window);
3319
3320 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003321 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3322 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003323
3324 // window is invalid, so it should not receive any input event.
3325 window->assertNoEvents();
3326}
3327
3328TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3329 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3330 sp<FakeWindowHandle> windowTop =
3331 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3332 sp<FakeWindowHandle> windowSecond =
3333 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3334 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3335
3336 windowTop->setFocusable(true);
3337 windowSecond->setFocusable(true);
3338 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3339 setFocusedWindow(windowTop);
3340 windowTop->consumeFocusEvent(true);
3341
3342 setFocusedWindow(windowSecond, windowTop);
3343 windowSecond->consumeFocusEvent(true);
3344 windowTop->consumeFocusEvent(false);
3345
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003346 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3347 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003348
3349 // Focused window should receive event.
3350 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3351}
3352
3353TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3354 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3355 sp<FakeWindowHandle> windowTop =
3356 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3357 sp<FakeWindowHandle> windowSecond =
3358 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3359 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3360
3361 windowTop->setFocusable(true);
3362 windowSecond->setFocusable(true);
3363 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3364 setFocusedWindow(windowSecond, windowTop);
3365
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003366 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3367 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003368
3369 // Event should be dropped.
3370 windowTop->assertNoEvents();
3371 windowSecond->assertNoEvents();
3372}
3373
3374TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3375 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3376 sp<FakeWindowHandle> window =
3377 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3378 sp<FakeWindowHandle> previousFocusedWindow =
3379 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3380 ADISPLAY_ID_DEFAULT);
3381 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3382
3383 window->setFocusable(true);
3384 previousFocusedWindow->setFocusable(true);
3385 window->setVisible(false);
3386 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3387 setFocusedWindow(previousFocusedWindow);
3388 previousFocusedWindow->consumeFocusEvent(true);
3389
3390 // Requesting focus on invisible window takes focus from currently focused window.
3391 setFocusedWindow(window);
3392 previousFocusedWindow->consumeFocusEvent(false);
3393
3394 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003395 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003396 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003397 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003398
3399 // Window does not get focus event or key down.
3400 window->assertNoEvents();
3401
3402 // Window becomes visible.
3403 window->setVisible(true);
3404 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3405
3406 // Window receives focus event.
3407 window->consumeFocusEvent(true);
3408 // Focused window receives key down.
3409 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3410}
3411
Vishnu Nair599f1412021-06-21 10:39:58 -07003412TEST_F(InputDispatcherTest, DisplayRemoved) {
3413 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3414 sp<FakeWindowHandle> window =
3415 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3416 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3417
3418 // window is granted focus.
3419 window->setFocusable(true);
3420 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3421 setFocusedWindow(window);
3422 window->consumeFocusEvent(true);
3423
3424 // When a display is removed window loses focus.
3425 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3426 window->consumeFocusEvent(false);
3427}
3428
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003429/**
3430 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3431 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3432 * of the 'slipperyEnterWindow'.
3433 *
3434 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3435 * a way so that the touched location is no longer covered by the top window.
3436 *
3437 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3438 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3439 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3440 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3441 * with ACTION_DOWN).
3442 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3443 * window moved itself away from the touched location and had Flag::SLIPPERY.
3444 *
3445 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3446 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3447 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3448 *
3449 * In this test, we ensure that the event received by the bottom window has
3450 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3451 */
3452TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3453 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3454 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3455
3456 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3457 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3458
3459 sp<FakeWindowHandle> slipperyExitWindow =
3460 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003461 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003462 // Make sure this one overlaps the bottom window
3463 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3464 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3465 // one. Windows with the same owner are not considered to be occluding each other.
3466 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3467
3468 sp<FakeWindowHandle> slipperyEnterWindow =
3469 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3470 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3471
3472 mDispatcher->setInputWindows(
3473 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3474
3475 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3476 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3477 ADISPLAY_ID_DEFAULT, {{50, 50}});
3478 mDispatcher->notifyMotion(&args);
3479 slipperyExitWindow->consumeMotionDown();
3480 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3481 mDispatcher->setInputWindows(
3482 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3483
3484 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3485 ADISPLAY_ID_DEFAULT, {{51, 51}});
3486 mDispatcher->notifyMotion(&args);
3487
3488 slipperyExitWindow->consumeMotionCancel();
3489
3490 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3491 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3492}
3493
Garfield Tan1c7bc862020-01-28 13:24:04 -08003494class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3495protected:
3496 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3497 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3498
Chris Yea209fde2020-07-22 13:54:51 -07003499 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003500 sp<FakeWindowHandle> mWindow;
3501
3502 virtual void SetUp() override {
3503 mFakePolicy = new FakeInputDispatcherPolicy();
3504 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003505 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003506 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3507 ASSERT_EQ(OK, mDispatcher->start());
3508
3509 setUpWindow();
3510 }
3511
3512 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003513 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003514 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3515
Vishnu Nair47074b82020-08-14 11:54:47 -07003516 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003517 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003518 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003519 mWindow->consumeFocusEvent(true);
3520 }
3521
Chris Ye2ad95392020-09-01 13:44:44 -07003522 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003523 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003524 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003525 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3526 mDispatcher->notifyKey(&keyArgs);
3527
3528 // Window should receive key down event.
3529 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3530 }
3531
3532 void expectKeyRepeatOnce(int32_t repeatCount) {
3533 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3534 InputEvent* repeatEvent = mWindow->consume();
3535 ASSERT_NE(nullptr, repeatEvent);
3536
3537 uint32_t eventType = repeatEvent->getType();
3538 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3539
3540 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3541 uint32_t eventAction = repeatKeyEvent->getAction();
3542 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3543 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3544 }
3545
Chris Ye2ad95392020-09-01 13:44:44 -07003546 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003547 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003548 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003549 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3550 mDispatcher->notifyKey(&keyArgs);
3551
3552 // Window should receive key down event.
3553 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3554 0 /*expectedFlags*/);
3555 }
3556};
3557
3558TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003559 sendAndConsumeKeyDown(1 /* deviceId */);
3560 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3561 expectKeyRepeatOnce(repeatCount);
3562 }
3563}
3564
3565TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3566 sendAndConsumeKeyDown(1 /* deviceId */);
3567 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3568 expectKeyRepeatOnce(repeatCount);
3569 }
3570 sendAndConsumeKeyDown(2 /* deviceId */);
3571 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003572 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3573 expectKeyRepeatOnce(repeatCount);
3574 }
3575}
3576
3577TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003578 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003579 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003580 sendAndConsumeKeyUp(1 /* deviceId */);
3581 mWindow->assertNoEvents();
3582}
3583
3584TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3585 sendAndConsumeKeyDown(1 /* deviceId */);
3586 expectKeyRepeatOnce(1 /*repeatCount*/);
3587 sendAndConsumeKeyDown(2 /* deviceId */);
3588 expectKeyRepeatOnce(1 /*repeatCount*/);
3589 // Stale key up from device 1.
3590 sendAndConsumeKeyUp(1 /* deviceId */);
3591 // Device 2 is still down, keep repeating
3592 expectKeyRepeatOnce(2 /*repeatCount*/);
3593 expectKeyRepeatOnce(3 /*repeatCount*/);
3594 // Device 2 key up
3595 sendAndConsumeKeyUp(2 /* deviceId */);
3596 mWindow->assertNoEvents();
3597}
3598
3599TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3600 sendAndConsumeKeyDown(1 /* deviceId */);
3601 expectKeyRepeatOnce(1 /*repeatCount*/);
3602 sendAndConsumeKeyDown(2 /* deviceId */);
3603 expectKeyRepeatOnce(1 /*repeatCount*/);
3604 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3605 sendAndConsumeKeyUp(2 /* deviceId */);
3606 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003607 mWindow->assertNoEvents();
3608}
3609
liushenxiang42232912021-05-21 20:24:09 +08003610TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3611 sendAndConsumeKeyDown(DEVICE_ID);
3612 expectKeyRepeatOnce(1 /*repeatCount*/);
3613 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3614 mDispatcher->notifyDeviceReset(&args);
3615 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3616 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3617 mWindow->assertNoEvents();
3618}
3619
Garfield Tan1c7bc862020-01-28 13:24:04 -08003620TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003621 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003622 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3623 InputEvent* repeatEvent = mWindow->consume();
3624 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3625 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3626 IdGenerator::getSource(repeatEvent->getId()));
3627 }
3628}
3629
3630TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003631 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003632
3633 std::unordered_set<int32_t> idSet;
3634 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3635 InputEvent* repeatEvent = mWindow->consume();
3636 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3637 int32_t id = repeatEvent->getId();
3638 EXPECT_EQ(idSet.end(), idSet.find(id));
3639 idSet.insert(id);
3640 }
3641}
3642
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003643/* Test InputDispatcher for MultiDisplay */
3644class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3645public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003646 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003647 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003648
Chris Yea209fde2020-07-22 13:54:51 -07003649 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003650 windowInPrimary =
3651 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003652
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003653 // Set focus window for primary display, but focused display would be second one.
3654 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003655 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003656 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003657 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003658 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003659
Chris Yea209fde2020-07-22 13:54:51 -07003660 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003661 windowInSecondary =
3662 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003663 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003664 // Set focus display to second one.
3665 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3666 // Set focus window for second display.
3667 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003668 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003669 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003670 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003671 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003672 }
3673
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003674 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003675 InputDispatcherTest::TearDown();
3676
Chris Yea209fde2020-07-22 13:54:51 -07003677 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003678 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003679 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003680 windowInSecondary.clear();
3681 }
3682
3683protected:
Chris Yea209fde2020-07-22 13:54:51 -07003684 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003685 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003686 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003687 sp<FakeWindowHandle> windowInSecondary;
3688};
3689
3690TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3691 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003692 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3693 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3694 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003695 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003696 windowInSecondary->assertNoEvents();
3697
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003698 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003699 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3700 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3701 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003702 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003703 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003704}
3705
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003706TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003707 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003708 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3709 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003710 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003711 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003712 windowInSecondary->assertNoEvents();
3713
3714 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003715 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003716 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003717 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003718 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003719
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003720 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003721 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003722
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003723 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003724 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3725 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003726
3727 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003728 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003729 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003730 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003731 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003732 windowInSecondary->assertNoEvents();
3733}
3734
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003735// Test per-display input monitors for motion event.
3736TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003737 FakeMonitorReceiver monitorInPrimary =
3738 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3739 FakeMonitorReceiver monitorInSecondary =
3740 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003741
3742 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003743 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3744 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3745 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003746 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003747 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003748 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003749 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003750
3751 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003752 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3753 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3754 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003755 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003756 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003757 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003758 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003759
3760 // Test inject a non-pointer motion event.
3761 // If specific a display, it will dispatch to the focused window of particular display,
3762 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003763 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3764 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3765 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003766 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003767 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003768 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003769 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003770}
3771
3772// Test per-display input monitors for key event.
3773TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003774 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003775 FakeMonitorReceiver monitorInPrimary =
3776 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3777 FakeMonitorReceiver monitorInSecondary =
3778 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003779
3780 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003781 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3782 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003783 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003784 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003785 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003786 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003787}
3788
Vishnu Nair958da932020-08-21 17:12:37 -07003789TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3790 sp<FakeWindowHandle> secondWindowInPrimary =
3791 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3792 secondWindowInPrimary->setFocusable(true);
3793 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3794 setFocusedWindow(secondWindowInPrimary);
3795 windowInPrimary->consumeFocusEvent(false);
3796 secondWindowInPrimary->consumeFocusEvent(true);
3797
3798 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003799 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3800 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003801 windowInPrimary->assertNoEvents();
3802 windowInSecondary->assertNoEvents();
3803 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3804}
3805
Jackal Guof9696682018-10-05 12:23:23 +08003806class InputFilterTest : public InputDispatcherTest {
3807protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003808 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3809 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003810 NotifyMotionArgs motionArgs;
3811
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003812 motionArgs =
3813 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003814 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003815 motionArgs =
3816 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003817 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003818 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003819 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003820 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3821 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003822 } else {
3823 mFakePolicy->assertFilterInputEventWasNotCalled();
3824 }
3825 }
3826
3827 void testNotifyKey(bool expectToBeFiltered) {
3828 NotifyKeyArgs keyArgs;
3829
3830 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3831 mDispatcher->notifyKey(&keyArgs);
3832 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3833 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003834 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003835
3836 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003837 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003838 } else {
3839 mFakePolicy->assertFilterInputEventWasNotCalled();
3840 }
3841 }
3842};
3843
3844// Test InputFilter for MotionEvent
3845TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3846 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3847 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3848 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3849
3850 // Enable InputFilter
3851 mDispatcher->setInputFilterEnabled(true);
3852 // Test touch on both primary and second display, and check if both events are filtered.
3853 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3854 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3855
3856 // Disable InputFilter
3857 mDispatcher->setInputFilterEnabled(false);
3858 // Test touch on both primary and second display, and check if both events aren't filtered.
3859 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3860 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3861}
3862
3863// Test InputFilter for KeyEvent
3864TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3865 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3866 testNotifyKey(/*expectToBeFiltered*/ false);
3867
3868 // Enable InputFilter
3869 mDispatcher->setInputFilterEnabled(true);
3870 // Send a key event, and check if it is filtered.
3871 testNotifyKey(/*expectToBeFiltered*/ true);
3872
3873 // Disable InputFilter
3874 mDispatcher->setInputFilterEnabled(false);
3875 // Send a key event, and check if it isn't filtered.
3876 testNotifyKey(/*expectToBeFiltered*/ false);
3877}
3878
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003879// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3880// logical display coordinate space.
3881TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3882 ui::Transform firstDisplayTransform;
3883 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3884 ui::Transform secondDisplayTransform;
3885 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3886
3887 std::vector<gui::DisplayInfo> displayInfos(2);
3888 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3889 displayInfos[0].transform = firstDisplayTransform;
3890 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3891 displayInfos[1].transform = secondDisplayTransform;
3892
3893 mDispatcher->onWindowInfosChanged({}, displayInfos);
3894
3895 // Enable InputFilter
3896 mDispatcher->setInputFilterEnabled(true);
3897
3898 // Ensure the correct transforms are used for the displays.
3899 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3900 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3901}
3902
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003903class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3904protected:
3905 virtual void SetUp() override {
3906 InputDispatcherTest::SetUp();
3907
3908 /**
3909 * We don't need to enable input filter to test the injected event policy, but we enabled it
3910 * here to make the tests more realistic, since this policy only matters when inputfilter is
3911 * on.
3912 */
3913 mDispatcher->setInputFilterEnabled(true);
3914
3915 std::shared_ptr<InputApplicationHandle> application =
3916 std::make_shared<FakeApplicationHandle>();
3917 mWindow =
3918 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3919
3920 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3921 mWindow->setFocusable(true);
3922 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3923 setFocusedWindow(mWindow);
3924 mWindow->consumeFocusEvent(true);
3925 }
3926
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003927 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3928 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003929 KeyEvent event;
3930
3931 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3932 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3933 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3934 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3935 const int32_t additionalPolicyFlags =
3936 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3937 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3938 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3939 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3940 policyFlags | additionalPolicyFlags));
3941
3942 InputEvent* received = mWindow->consume();
3943 ASSERT_NE(nullptr, received);
3944 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003945 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3946 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3947 ASSERT_EQ(flags, keyEvent.getFlags());
3948 }
3949
3950 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3951 int32_t flags) {
3952 MotionEvent event;
3953 PointerProperties pointerProperties[1];
3954 PointerCoords pointerCoords[1];
3955 pointerProperties[0].clear();
3956 pointerProperties[0].id = 0;
3957 pointerCoords[0].clear();
3958 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3959 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3960
3961 ui::Transform identityTransform;
3962 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3963 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3964 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3965 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3966 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003967 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003968 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003969 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3970
3971 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3972 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3973 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3974 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3975 policyFlags | additionalPolicyFlags));
3976
3977 InputEvent* received = mWindow->consume();
3978 ASSERT_NE(nullptr, received);
3979 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3980 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3981 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3982 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003983 }
3984
3985private:
3986 sp<FakeWindowHandle> mWindow;
3987};
3988
3989TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003990 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3991 // filter. Without it, the event will no different from a regularly injected event, and the
3992 // injected device id will be overwritten.
3993 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3994 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003995}
3996
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003997TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003998 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003999 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4000 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4001}
4002
4003TEST_F(InputFilterInjectionPolicyTest,
4004 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4005 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4006 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4007 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004008}
4009
4010TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4011 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004012 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004013}
4014
chaviwfd6d3512019-03-25 13:23:49 -07004015class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004016 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004017 InputDispatcherTest::SetUp();
4018
Chris Yea209fde2020-07-22 13:54:51 -07004019 std::shared_ptr<FakeApplicationHandle> application =
4020 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004021 mUnfocusedWindow =
4022 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004023 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4024 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4025 // window.
chaviw3277faf2021-05-19 16:45:23 -05004026 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07004027
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004028 mFocusedWindow =
4029 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4030 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004031 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07004032
4033 // Set focused application.
4034 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004035 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004036
4037 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004038 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004039 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004040 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004041 }
4042
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004043 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004044 InputDispatcherTest::TearDown();
4045
4046 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004047 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004048 }
4049
4050protected:
4051 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004052 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004053 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004054};
4055
4056// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4057// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4058// the onPointerDownOutsideFocus callback.
4059TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004060 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004061 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4062 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004063 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004064 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004065
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004066 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004067 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4068}
4069
4070// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4071// DOWN on the window that doesn't have focus. Ensure no window received the
4072// onPointerDownOutsideFocus callback.
4073TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004074 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004075 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004076 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004077 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004078
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004079 ASSERT_TRUE(mDispatcher->waitForIdle());
4080 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004081}
4082
4083// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4084// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4085TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004086 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4087 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004088 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004089 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004090
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004091 ASSERT_TRUE(mDispatcher->waitForIdle());
4092 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004093}
4094
4095// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4096// DOWN on the window that already has focus. Ensure no window received the
4097// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004098TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004099 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004100 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004101 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004102 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004103 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004104
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004105 ASSERT_TRUE(mDispatcher->waitForIdle());
4106 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004107}
4108
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004109// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4110// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4111TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4112 const MotionEvent event =
4113 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4114 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4115 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4116 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4117 .build();
4118 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4119 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4120 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4121
4122 ASSERT_TRUE(mDispatcher->waitForIdle());
4123 mFakePolicy->assertOnPointerDownWasNotCalled();
4124 // Ensure that the unfocused window did not receive any FOCUS events.
4125 mUnfocusedWindow->assertNoEvents();
4126}
4127
chaviwaf87b3e2019-10-01 16:59:28 -07004128// These tests ensures we can send touch events to a single client when there are multiple input
4129// windows that point to the same client token.
4130class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4131 virtual void SetUp() override {
4132 InputDispatcherTest::SetUp();
4133
Chris Yea209fde2020-07-22 13:54:51 -07004134 std::shared_ptr<FakeApplicationHandle> application =
4135 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004136 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4137 ADISPLAY_ID_DEFAULT);
4138 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
4139 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05004140 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004141 mWindow1->setFrame(Rect(0, 0, 100, 100));
4142
4143 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4144 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05004145 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004146 mWindow2->setFrame(Rect(100, 100, 200, 200));
4147
Arthur Hung72d8dc32020-03-28 00:48:39 +00004148 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004149 }
4150
4151protected:
4152 sp<FakeWindowHandle> mWindow1;
4153 sp<FakeWindowHandle> mWindow2;
4154
4155 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004156 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004157 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4158 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004159 }
4160
4161 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4162 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004163 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004164 InputEvent* event = window->consume();
4165
4166 ASSERT_NE(nullptr, event) << name.c_str()
4167 << ": consumer should have returned non-NULL event.";
4168
4169 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4170 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4171 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4172
4173 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004174 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004175
4176 for (size_t i = 0; i < points.size(); i++) {
4177 float expectedX = points[i].x;
4178 float expectedY = points[i].y;
4179
4180 EXPECT_EQ(expectedX, motionEvent.getX(i))
4181 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4182 << ", got " << motionEvent.getX(i);
4183 EXPECT_EQ(expectedY, motionEvent.getY(i))
4184 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4185 << ", got " << motionEvent.getY(i);
4186 }
4187 }
chaviw9eaa22c2020-07-01 16:21:27 -07004188
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004189 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004190 std::vector<PointF> expectedPoints) {
4191 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4192 ADISPLAY_ID_DEFAULT, touchedPoints);
4193 mDispatcher->notifyMotion(&motionArgs);
4194
4195 // Always consume from window1 since it's the window that has the InputReceiver
4196 consumeMotionEvent(mWindow1, action, expectedPoints);
4197 }
chaviwaf87b3e2019-10-01 16:59:28 -07004198};
4199
4200TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4201 // Touch Window 1
4202 PointF touchedPoint = {10, 10};
4203 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004204 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004205
4206 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004207 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004208
4209 // Touch Window 2
4210 touchedPoint = {150, 150};
4211 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004212 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004213}
4214
chaviw9eaa22c2020-07-01 16:21:27 -07004215TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4216 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004217 mWindow2->setWindowScale(0.5f, 0.5f);
4218
4219 // Touch Window 1
4220 PointF touchedPoint = {10, 10};
4221 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004222 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004223 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004224 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004225
4226 // Touch Window 2
4227 touchedPoint = {150, 150};
4228 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004229 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4230 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004231
chaviw9eaa22c2020-07-01 16:21:27 -07004232 // Update the transform so rotation is set
4233 mWindow2->setWindowTransform(0, -1, 1, 0);
4234 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4235 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004236}
4237
chaviw9eaa22c2020-07-01 16:21:27 -07004238TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004239 mWindow2->setWindowScale(0.5f, 0.5f);
4240
4241 // Touch Window 1
4242 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4243 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004244 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004245
4246 // Touch Window 2
4247 int32_t actionPointerDown =
4248 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004249 touchedPoints.push_back(PointF{150, 150});
4250 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4251 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004252
chaviw9eaa22c2020-07-01 16:21:27 -07004253 // Release Window 2
4254 int32_t actionPointerUp =
4255 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4256 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4257 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004258
chaviw9eaa22c2020-07-01 16:21:27 -07004259 // Update the transform so rotation is set for Window 2
4260 mWindow2->setWindowTransform(0, -1, 1, 0);
4261 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4262 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004263}
4264
chaviw9eaa22c2020-07-01 16:21:27 -07004265TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004266 mWindow2->setWindowScale(0.5f, 0.5f);
4267
4268 // Touch Window 1
4269 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4270 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004271 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004272
4273 // Touch Window 2
4274 int32_t actionPointerDown =
4275 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004276 touchedPoints.push_back(PointF{150, 150});
4277 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004278
chaviw9eaa22c2020-07-01 16:21:27 -07004279 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004280
4281 // Move both windows
4282 touchedPoints = {{20, 20}, {175, 175}};
4283 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4284 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4285
chaviw9eaa22c2020-07-01 16:21:27 -07004286 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004287
chaviw9eaa22c2020-07-01 16:21:27 -07004288 // Release Window 2
4289 int32_t actionPointerUp =
4290 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4291 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4292 expectedPoints.pop_back();
4293
4294 // Touch Window 2
4295 mWindow2->setWindowTransform(0, -1, 1, 0);
4296 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4297 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4298
4299 // Move both windows
4300 touchedPoints = {{20, 20}, {175, 175}};
4301 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4302 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4303
4304 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004305}
4306
4307TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4308 mWindow1->setWindowScale(0.5f, 0.5f);
4309
4310 // Touch Window 1
4311 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4312 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004313 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004314
4315 // Touch Window 2
4316 int32_t actionPointerDown =
4317 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004318 touchedPoints.push_back(PointF{150, 150});
4319 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004320
chaviw9eaa22c2020-07-01 16:21:27 -07004321 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004322
4323 // Move both windows
4324 touchedPoints = {{20, 20}, {175, 175}};
4325 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4326 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4327
chaviw9eaa22c2020-07-01 16:21:27 -07004328 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004329}
4330
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004331class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4332 virtual void SetUp() override {
4333 InputDispatcherTest::SetUp();
4334
Chris Yea209fde2020-07-22 13:54:51 -07004335 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004336 mApplication->setDispatchingTimeout(20ms);
4337 mWindow =
4338 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4339 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004340 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004341 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004342 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4343 // window.
chaviw3277faf2021-05-19 16:45:23 -05004344 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004345
4346 // Set focused application.
4347 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4348
4349 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004350 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004351 mWindow->consumeFocusEvent(true);
4352 }
4353
4354 virtual void TearDown() override {
4355 InputDispatcherTest::TearDown();
4356 mWindow.clear();
4357 }
4358
4359protected:
Chris Yea209fde2020-07-22 13:54:51 -07004360 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004361 sp<FakeWindowHandle> mWindow;
4362 static constexpr PointF WINDOW_LOCATION = {20, 20};
4363
4364 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004365 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004366 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4367 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004368 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004369 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4370 WINDOW_LOCATION));
4371 }
4372};
4373
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004374// Send a tap and respond, which should not cause an ANR.
4375TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4376 tapOnWindow();
4377 mWindow->consumeMotionDown();
4378 mWindow->consumeMotionUp();
4379 ASSERT_TRUE(mDispatcher->waitForIdle());
4380 mFakePolicy->assertNotifyAnrWasNotCalled();
4381}
4382
4383// Send a regular key and respond, which should not cause an ANR.
4384TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004385 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004386 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4387 ASSERT_TRUE(mDispatcher->waitForIdle());
4388 mFakePolicy->assertNotifyAnrWasNotCalled();
4389}
4390
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004391TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4392 mWindow->setFocusable(false);
4393 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4394 mWindow->consumeFocusEvent(false);
4395
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004396 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004397 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004398 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4399 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004400 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004401 // Key will not go to window because we have no focused window.
4402 // The 'no focused window' ANR timer should start instead.
4403
4404 // Now, the focused application goes away.
4405 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4406 // The key should get dropped and there should be no ANR.
4407
4408 ASSERT_TRUE(mDispatcher->waitForIdle());
4409 mFakePolicy->assertNotifyAnrWasNotCalled();
4410}
4411
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004412// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004413// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4414// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004415TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004416 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004417 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4418 WINDOW_LOCATION));
4419
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004420 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4421 ASSERT_TRUE(sequenceNum);
4422 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004423 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004424
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004425 mWindow->finishEvent(*sequenceNum);
4426 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4427 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004428 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004429 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004430}
4431
4432// Send a key to the app and have the app not respond right away.
4433TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4434 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004435 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004436 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4437 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004438 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004439 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004440 ASSERT_TRUE(mDispatcher->waitForIdle());
4441}
4442
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004443// We have a focused application, but no focused window
4444TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004445 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004446 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4447 mWindow->consumeFocusEvent(false);
4448
4449 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004450 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004451 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4452 WINDOW_LOCATION));
4453 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4454 mDispatcher->waitForIdle();
4455 mFakePolicy->assertNotifyAnrWasNotCalled();
4456
4457 // Once a focused event arrives, we get an ANR for this application
4458 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4459 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004460 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004461 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004462 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004463 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004464 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004465 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004466 ASSERT_TRUE(mDispatcher->waitForIdle());
4467}
4468
4469// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004470// Make sure that we don't notify policy twice about the same ANR.
4471TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004472 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004473 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4474 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004475
4476 // Once a focused event arrives, we get an ANR for this application
4477 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4478 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004479 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004480 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004481 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004482 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004483 const std::chrono::duration appTimeout =
4484 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004485 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004486
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004487 std::this_thread::sleep_for(appTimeout);
4488 // ANR should not be raised again. It is up to policy to do that if it desires.
4489 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004490
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004491 // If we now get a focused window, the ANR should stop, but the policy handles that via
4492 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004493 ASSERT_TRUE(mDispatcher->waitForIdle());
4494}
4495
4496// We have a focused application, but no focused window
4497TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004498 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004499 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4500 mWindow->consumeFocusEvent(false);
4501
4502 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004503 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004504 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004505 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4506 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004507
4508 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004509 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004510
4511 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004512 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004513 ASSERT_TRUE(mDispatcher->waitForIdle());
4514 mWindow->assertNoEvents();
4515}
4516
4517/**
4518 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4519 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4520 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4521 * the ANR mechanism should still work.
4522 *
4523 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4524 * DOWN event, while not responding on the second one.
4525 */
4526TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4527 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4528 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4529 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4530 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4531 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004532 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004533
4534 // Now send ACTION_UP, with identical timestamp
4535 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4536 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4537 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4538 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004539 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004540
4541 // We have now sent down and up. Let's consume first event and then ANR on the second.
4542 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4543 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004544 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004545}
4546
4547// If an app is not responding to a key event, gesture monitors should continue to receive
4548// new motion events
4549TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
4550 FakeMonitorReceiver monitor =
4551 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4552 true /*isGestureMonitor*/);
4553
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004554 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4555 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004556 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004557 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004558
4559 // Stuck on the ACTION_UP
4560 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004561 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004562
4563 // New tap will go to the gesture monitor, but not to the window
4564 tapOnWindow();
4565 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4566 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4567
4568 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4569 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004570 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004571 mWindow->assertNoEvents();
4572 monitor.assertNoEvents();
4573}
4574
4575// If an app is not responding to a motion event, gesture monitors should continue to receive
4576// new motion events
4577TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
4578 FakeMonitorReceiver monitor =
4579 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4580 true /*isGestureMonitor*/);
4581
4582 tapOnWindow();
4583 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4584 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4585
4586 mWindow->consumeMotionDown();
4587 // Stuck on the ACTION_UP
4588 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004589 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004590
4591 // New tap will go to the gesture monitor, but not to the window
4592 tapOnWindow();
4593 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4594 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4595
4596 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4597 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004598 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004599 mWindow->assertNoEvents();
4600 monitor.assertNoEvents();
4601}
4602
4603// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4604// process events, you don't get an anr. When the window later becomes unresponsive again, you
4605// get an ANR again.
4606// 1. tap -> block on ACTION_UP -> receive ANR
4607// 2. consume all pending events (= queue becomes healthy again)
4608// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4609TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4610 tapOnWindow();
4611
4612 mWindow->consumeMotionDown();
4613 // Block on ACTION_UP
4614 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004615 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004616 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4617 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004618 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004619 mWindow->assertNoEvents();
4620
4621 tapOnWindow();
4622 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004623 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004624 mWindow->consumeMotionUp();
4625
4626 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004627 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004628 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004629 mWindow->assertNoEvents();
4630}
4631
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004632// If a connection remains unresponsive for a while, make sure policy is only notified once about
4633// it.
4634TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004635 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004636 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4637 WINDOW_LOCATION));
4638
4639 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004640 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004641 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004642 // 'notifyConnectionUnresponsive' should only be called once per connection
4643 mFakePolicy->assertNotifyAnrWasNotCalled();
4644 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004645 mWindow->consumeMotionDown();
4646 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4647 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4648 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004649 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004650 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004651 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004652}
4653
4654/**
4655 * If a window is processing a motion event, and then a key event comes in, the key event should
4656 * not to to the focused window until the motion is processed.
4657 *
4658 * Warning!!!
4659 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4660 * and the injection timeout that we specify when injecting the key.
4661 * We must have the injection timeout (10ms) be smaller than
4662 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4663 *
4664 * If that value changes, this test should also change.
4665 */
4666TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4667 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4668 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4669
4670 tapOnWindow();
4671 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4672 ASSERT_TRUE(downSequenceNum);
4673 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4674 ASSERT_TRUE(upSequenceNum);
4675 // Don't finish the events yet, and send a key
4676 // Injection will "succeed" because we will eventually give up and send the key to the focused
4677 // window even if motions are still being processed. But because the injection timeout is short,
4678 // we will receive INJECTION_TIMED_OUT as the result.
4679
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004680 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004681 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004682 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4683 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004684 // Key will not be sent to the window, yet, because the window is still processing events
4685 // and the key remains pending, waiting for the touch events to be processed
4686 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4687 ASSERT_FALSE(keySequenceNum);
4688
4689 std::this_thread::sleep_for(500ms);
4690 // if we wait long enough though, dispatcher will give up, and still send the key
4691 // to the focused window, even though we have not yet finished the motion event
4692 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4693 mWindow->finishEvent(*downSequenceNum);
4694 mWindow->finishEvent(*upSequenceNum);
4695}
4696
4697/**
4698 * If a window is processing a motion event, and then a key event comes in, the key event should
4699 * not go to the focused window until the motion is processed.
4700 * If then a new motion comes in, then the pending key event should be going to the currently
4701 * focused window right away.
4702 */
4703TEST_F(InputDispatcherSingleWindowAnr,
4704 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4705 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4706 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4707
4708 tapOnWindow();
4709 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4710 ASSERT_TRUE(downSequenceNum);
4711 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4712 ASSERT_TRUE(upSequenceNum);
4713 // Don't finish the events yet, and send a key
4714 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004715 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004716 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004717 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004718 // At this point, key is still pending, and should not be sent to the application yet.
4719 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4720 ASSERT_FALSE(keySequenceNum);
4721
4722 // Now tap down again. It should cause the pending key to go to the focused window right away.
4723 tapOnWindow();
4724 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4725 // the other events yet. We can finish events in any order.
4726 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4727 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4728 mWindow->consumeMotionDown();
4729 mWindow->consumeMotionUp();
4730 mWindow->assertNoEvents();
4731}
4732
4733class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4734 virtual void SetUp() override {
4735 InputDispatcherTest::SetUp();
4736
Chris Yea209fde2020-07-22 13:54:51 -07004737 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004738 mApplication->setDispatchingTimeout(10ms);
4739 mUnfocusedWindow =
4740 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4741 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4742 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4743 // window.
4744 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004745 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4746 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4747 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004748
4749 mFocusedWindow =
4750 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004751 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004752 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004753 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004754
4755 // Set focused application.
4756 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004757 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004758
4759 // Expect one focus window exist in display.
4760 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004761 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004762 mFocusedWindow->consumeFocusEvent(true);
4763 }
4764
4765 virtual void TearDown() override {
4766 InputDispatcherTest::TearDown();
4767
4768 mUnfocusedWindow.clear();
4769 mFocusedWindow.clear();
4770 }
4771
4772protected:
Chris Yea209fde2020-07-22 13:54:51 -07004773 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004774 sp<FakeWindowHandle> mUnfocusedWindow;
4775 sp<FakeWindowHandle> mFocusedWindow;
4776 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4777 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4778 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4779
4780 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4781
4782 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4783
4784private:
4785 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004786 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004787 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4788 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004789 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004790 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4791 location));
4792 }
4793};
4794
4795// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4796// should be ANR'd first.
4797TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004798 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004799 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4800 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004801 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004802 mFocusedWindow->consumeMotionDown();
4803 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4804 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4805 // We consumed all events, so no ANR
4806 ASSERT_TRUE(mDispatcher->waitForIdle());
4807 mFakePolicy->assertNotifyAnrWasNotCalled();
4808
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004809 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004810 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4811 FOCUSED_WINDOW_LOCATION));
4812 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4813 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004814
4815 const std::chrono::duration timeout =
4816 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004817 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004818 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4819 // sequence to make it consistent
4820 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004821 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004822 mFocusedWindow->consumeMotionDown();
4823 // This cancel is generated because the connection was unresponsive
4824 mFocusedWindow->consumeMotionCancel();
4825 mFocusedWindow->assertNoEvents();
4826 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004827 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004828 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004829 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004830}
4831
4832// If we have 2 windows with identical timeouts that are both unresponsive,
4833// it doesn't matter which order they should have ANR.
4834// But we should receive ANR for both.
4835TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4836 // Set the timeout for unfocused window to match the focused window
4837 mUnfocusedWindow->setDispatchingTimeout(10ms);
4838 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4839
4840 tapOnFocusedWindow();
4841 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004842 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4843 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004844
4845 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004846 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4847 mFocusedWindow->getToken() == anrConnectionToken2);
4848 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4849 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004850
4851 ASSERT_TRUE(mDispatcher->waitForIdle());
4852 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004853
4854 mFocusedWindow->consumeMotionDown();
4855 mFocusedWindow->consumeMotionUp();
4856 mUnfocusedWindow->consumeMotionOutside();
4857
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004858 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4859 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004860
4861 // Both applications should be marked as responsive, in any order
4862 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4863 mFocusedWindow->getToken() == responsiveToken2);
4864 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4865 mUnfocusedWindow->getToken() == responsiveToken2);
4866 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004867}
4868
4869// If a window is already not responding, the second tap on the same window should be ignored.
4870// We should also log an error to account for the dropped event (not tested here).
4871// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4872TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4873 tapOnFocusedWindow();
4874 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4875 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4876 // Receive the events, but don't respond
4877 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4878 ASSERT_TRUE(downEventSequenceNum);
4879 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4880 ASSERT_TRUE(upEventSequenceNum);
4881 const std::chrono::duration timeout =
4882 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004883 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004884
4885 // Tap once again
4886 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004887 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004888 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4889 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004890 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004891 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4892 FOCUSED_WINDOW_LOCATION));
4893 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4894 // valid touch target
4895 mUnfocusedWindow->assertNoEvents();
4896
4897 // Consume the first tap
4898 mFocusedWindow->finishEvent(*downEventSequenceNum);
4899 mFocusedWindow->finishEvent(*upEventSequenceNum);
4900 ASSERT_TRUE(mDispatcher->waitForIdle());
4901 // The second tap did not go to the focused window
4902 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004903 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004904 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004905 mFakePolicy->assertNotifyAnrWasNotCalled();
4906}
4907
4908// If you tap outside of all windows, there will not be ANR
4909TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004910 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004911 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4912 LOCATION_OUTSIDE_ALL_WINDOWS));
4913 ASSERT_TRUE(mDispatcher->waitForIdle());
4914 mFakePolicy->assertNotifyAnrWasNotCalled();
4915}
4916
4917// Since the focused window is paused, tapping on it should not produce any events
4918TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4919 mFocusedWindow->setPaused(true);
4920 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4921
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004922 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004923 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4924 FOCUSED_WINDOW_LOCATION));
4925
4926 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4927 ASSERT_TRUE(mDispatcher->waitForIdle());
4928 // Should not ANR because the window is paused, and touches shouldn't go to it
4929 mFakePolicy->assertNotifyAnrWasNotCalled();
4930
4931 mFocusedWindow->assertNoEvents();
4932 mUnfocusedWindow->assertNoEvents();
4933}
4934
4935/**
4936 * If a window is processing a motion event, and then a key event comes in, the key event should
4937 * not to to the focused window until the motion is processed.
4938 * If a different window becomes focused at this time, the key should go to that window instead.
4939 *
4940 * Warning!!!
4941 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4942 * and the injection timeout that we specify when injecting the key.
4943 * We must have the injection timeout (10ms) be smaller than
4944 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4945 *
4946 * If that value changes, this test should also change.
4947 */
4948TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4949 // Set a long ANR timeout to prevent it from triggering
4950 mFocusedWindow->setDispatchingTimeout(2s);
4951 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4952
4953 tapOnUnfocusedWindow();
4954 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4955 ASSERT_TRUE(downSequenceNum);
4956 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4957 ASSERT_TRUE(upSequenceNum);
4958 // Don't finish the events yet, and send a key
4959 // Injection will succeed because we will eventually give up and send the key to the focused
4960 // window even if motions are still being processed.
4961
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004962 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004963 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004964 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4965 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004966 // Key will not be sent to the window, yet, because the window is still processing events
4967 // and the key remains pending, waiting for the touch events to be processed
4968 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4969 ASSERT_FALSE(keySequenceNum);
4970
4971 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004972 mFocusedWindow->setFocusable(false);
4973 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004974 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004975 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004976
4977 // Focus events should precede the key events
4978 mUnfocusedWindow->consumeFocusEvent(true);
4979 mFocusedWindow->consumeFocusEvent(false);
4980
4981 // Finish the tap events, which should unblock dispatcher
4982 mUnfocusedWindow->finishEvent(*downSequenceNum);
4983 mUnfocusedWindow->finishEvent(*upSequenceNum);
4984
4985 // Now that all queues are cleared and no backlog in the connections, the key event
4986 // can finally go to the newly focused "mUnfocusedWindow".
4987 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4988 mFocusedWindow->assertNoEvents();
4989 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004990 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004991}
4992
4993// When the touch stream is split across 2 windows, and one of them does not respond,
4994// then ANR should be raised and the touch should be canceled for the unresponsive window.
4995// The other window should not be affected by that.
4996TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4997 // Touch Window 1
4998 NotifyMotionArgs motionArgs =
4999 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5000 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5001 mDispatcher->notifyMotion(&motionArgs);
5002 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5003 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5004
5005 // Touch Window 2
5006 int32_t actionPointerDown =
5007 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
5008
5009 motionArgs =
5010 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5011 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
5012 mDispatcher->notifyMotion(&motionArgs);
5013
5014 const std::chrono::duration timeout =
5015 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005016 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005017
5018 mUnfocusedWindow->consumeMotionDown();
5019 mFocusedWindow->consumeMotionDown();
5020 // Focused window may or may not receive ACTION_MOVE
5021 // But it should definitely receive ACTION_CANCEL due to the ANR
5022 InputEvent* event;
5023 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5024 ASSERT_TRUE(moveOrCancelSequenceNum);
5025 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5026 ASSERT_NE(nullptr, event);
5027 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5028 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5029 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5030 mFocusedWindow->consumeMotionCancel();
5031 } else {
5032 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5033 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005034 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005035 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005036
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005037 mUnfocusedWindow->assertNoEvents();
5038 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005039 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005040}
5041
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005042/**
5043 * If we have no focused window, and a key comes in, we start the ANR timer.
5044 * The focused application should add a focused window before the timer runs out to prevent ANR.
5045 *
5046 * If the user touches another application during this time, the key should be dropped.
5047 * Next, if a new focused window comes in, without toggling the focused application,
5048 * then no ANR should occur.
5049 *
5050 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5051 * but in some cases the policy may not update the focused application.
5052 */
5053TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5054 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5055 std::make_shared<FakeApplicationHandle>();
5056 focusedApplication->setDispatchingTimeout(60ms);
5057 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5058 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5059 mFocusedWindow->setFocusable(false);
5060
5061 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5062 mFocusedWindow->consumeFocusEvent(false);
5063
5064 // Send a key. The ANR timer should start because there is no focused window.
5065 // 'focusedApplication' will get blamed if this timer completes.
5066 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005067 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005068 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005069 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5070 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005071 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005072
5073 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5074 // then the injected touches won't cause the focused event to get dropped.
5075 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5076 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5077 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5078 // For this test, it means that the key would get delivered to the window once it becomes
5079 // focused.
5080 std::this_thread::sleep_for(10ms);
5081
5082 // Touch unfocused window. This should force the pending key to get dropped.
5083 NotifyMotionArgs motionArgs =
5084 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5085 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5086 mDispatcher->notifyMotion(&motionArgs);
5087
5088 // We do not consume the motion right away, because that would require dispatcher to first
5089 // process (== drop) the key event, and by that time, ANR will be raised.
5090 // Set the focused window first.
5091 mFocusedWindow->setFocusable(true);
5092 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5093 setFocusedWindow(mFocusedWindow);
5094 mFocusedWindow->consumeFocusEvent(true);
5095 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5096 // to another application. This could be a bug / behaviour in the policy.
5097
5098 mUnfocusedWindow->consumeMotionDown();
5099
5100 ASSERT_TRUE(mDispatcher->waitForIdle());
5101 // Should not ANR because we actually have a focused window. It was just added too slowly.
5102 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5103}
5104
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005105// These tests ensure we cannot send touch events to a window that's positioned behind a window
5106// that has feature NO_INPUT_CHANNEL.
5107// Layout:
5108// Top (closest to user)
5109// mNoInputWindow (above all windows)
5110// mBottomWindow
5111// Bottom (furthest from user)
5112class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5113 virtual void SetUp() override {
5114 InputDispatcherTest::SetUp();
5115
5116 mApplication = std::make_shared<FakeApplicationHandle>();
5117 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5118 "Window without input channel", ADISPLAY_ID_DEFAULT,
5119 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5120
chaviw3277faf2021-05-19 16:45:23 -05005121 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005122 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5123 // It's perfectly valid for this window to not have an associated input channel
5124
5125 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5126 ADISPLAY_ID_DEFAULT);
5127 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5128
5129 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5130 }
5131
5132protected:
5133 std::shared_ptr<FakeApplicationHandle> mApplication;
5134 sp<FakeWindowHandle> mNoInputWindow;
5135 sp<FakeWindowHandle> mBottomWindow;
5136};
5137
5138TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5139 PointF touchedPoint = {10, 10};
5140
5141 NotifyMotionArgs motionArgs =
5142 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5143 ADISPLAY_ID_DEFAULT, {touchedPoint});
5144 mDispatcher->notifyMotion(&motionArgs);
5145
5146 mNoInputWindow->assertNoEvents();
5147 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5148 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5149 // and therefore should prevent mBottomWindow from receiving touches
5150 mBottomWindow->assertNoEvents();
5151}
5152
5153/**
5154 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5155 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5156 */
5157TEST_F(InputDispatcherMultiWindowOcclusionTests,
5158 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5159 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5160 "Window with input channel and NO_INPUT_CHANNEL",
5161 ADISPLAY_ID_DEFAULT);
5162
chaviw3277faf2021-05-19 16:45:23 -05005163 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005164 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5165 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5166
5167 PointF touchedPoint = {10, 10};
5168
5169 NotifyMotionArgs motionArgs =
5170 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5171 ADISPLAY_ID_DEFAULT, {touchedPoint});
5172 mDispatcher->notifyMotion(&motionArgs);
5173
5174 mNoInputWindow->assertNoEvents();
5175 mBottomWindow->assertNoEvents();
5176}
5177
Vishnu Nair958da932020-08-21 17:12:37 -07005178class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5179protected:
5180 std::shared_ptr<FakeApplicationHandle> mApp;
5181 sp<FakeWindowHandle> mWindow;
5182 sp<FakeWindowHandle> mMirror;
5183
5184 virtual void SetUp() override {
5185 InputDispatcherTest::SetUp();
5186 mApp = std::make_shared<FakeApplicationHandle>();
5187 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5188 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5189 mWindow->getToken());
5190 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5191 mWindow->setFocusable(true);
5192 mMirror->setFocusable(true);
5193 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5194 }
5195};
5196
5197TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5198 // Request focus on a mirrored window
5199 setFocusedWindow(mMirror);
5200
5201 // window gets focused
5202 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005203 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5204 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005205 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5206}
5207
5208// A focused & mirrored window remains focused only if the window and its mirror are both
5209// focusable.
5210TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5211 setFocusedWindow(mMirror);
5212
5213 // window gets focused
5214 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005215 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5216 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005217 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005218 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5219 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005220 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5221
5222 mMirror->setFocusable(false);
5223 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5224
5225 // window loses focus since one of the windows associated with the token in not focusable
5226 mWindow->consumeFocusEvent(false);
5227
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005228 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5229 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005230 mWindow->assertNoEvents();
5231}
5232
5233// A focused & mirrored window remains focused until the window and its mirror both become
5234// invisible.
5235TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5236 setFocusedWindow(mMirror);
5237
5238 // window gets focused
5239 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005240 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5241 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005242 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005243 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5244 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005245 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5246
5247 mMirror->setVisible(false);
5248 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5249
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005250 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5251 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005252 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005253 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5254 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005255 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5256
5257 mWindow->setVisible(false);
5258 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5259
5260 // window loses focus only after all windows associated with the token become invisible.
5261 mWindow->consumeFocusEvent(false);
5262
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005263 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5264 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005265 mWindow->assertNoEvents();
5266}
5267
5268// A focused & mirrored window remains focused until both windows are removed.
5269TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5270 setFocusedWindow(mMirror);
5271
5272 // window gets focused
5273 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005274 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5275 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005276 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005277 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5278 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005279 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5280
5281 // single window is removed but the window token remains focused
5282 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5283
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 // Both windows are removed
5292 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5293 mWindow->consumeFocusEvent(false);
5294
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005295 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5296 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005297 mWindow->assertNoEvents();
5298}
5299
5300// Focus request can be pending until one window becomes visible.
5301TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5302 // Request focus on an invisible mirror.
5303 mWindow->setVisible(false);
5304 mMirror->setVisible(false);
5305 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5306 setFocusedWindow(mMirror);
5307
5308 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005309 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005310 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005311 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005312
5313 mMirror->setVisible(true);
5314 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5315
5316 // window gets focused
5317 mWindow->consumeFocusEvent(true);
5318 // window gets the pending key event
5319 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5320}
Prabir Pradhan99987712020-11-10 18:43:05 -08005321
5322class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5323protected:
5324 std::shared_ptr<FakeApplicationHandle> mApp;
5325 sp<FakeWindowHandle> mWindow;
5326 sp<FakeWindowHandle> mSecondWindow;
5327
5328 void SetUp() override {
5329 InputDispatcherTest::SetUp();
5330 mApp = std::make_shared<FakeApplicationHandle>();
5331 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5332 mWindow->setFocusable(true);
5333 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5334 mSecondWindow->setFocusable(true);
5335
5336 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5337 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5338
5339 setFocusedWindow(mWindow);
5340 mWindow->consumeFocusEvent(true);
5341 }
5342
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005343 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5344 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005345 mDispatcher->notifyPointerCaptureChanged(&args);
5346 }
5347
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005348 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5349 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005350 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005351 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5352 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005353 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005354 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005355 }
5356};
5357
5358TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5359 // Ensure that capture cannot be obtained for unfocused windows.
5360 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5361 mFakePolicy->assertSetPointerCaptureNotCalled();
5362 mSecondWindow->assertNoEvents();
5363
5364 // Ensure that capture can be enabled from the focus window.
5365 requestAndVerifyPointerCapture(mWindow, true);
5366
5367 // Ensure that capture cannot be disabled from a window that does not have capture.
5368 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5369 mFakePolicy->assertSetPointerCaptureNotCalled();
5370
5371 // Ensure that capture can be disabled from the window with capture.
5372 requestAndVerifyPointerCapture(mWindow, false);
5373}
5374
5375TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005376 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005377
5378 setFocusedWindow(mSecondWindow);
5379
5380 // Ensure that the capture disabled event was sent first.
5381 mWindow->consumeCaptureEvent(false);
5382 mWindow->consumeFocusEvent(false);
5383 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005384 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005385
5386 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005387 notifyPointerCaptureChanged({});
5388 notifyPointerCaptureChanged(request);
5389 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005390 mWindow->assertNoEvents();
5391 mSecondWindow->assertNoEvents();
5392 mFakePolicy->assertSetPointerCaptureNotCalled();
5393}
5394
5395TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005396 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005397
5398 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005399 notifyPointerCaptureChanged({});
5400 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005401
5402 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005403 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005404 mWindow->consumeCaptureEvent(false);
5405 mWindow->assertNoEvents();
5406}
5407
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005408TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5409 requestAndVerifyPointerCapture(mWindow, true);
5410
5411 // The first window loses focus.
5412 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005413 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005414 mWindow->consumeCaptureEvent(false);
5415
5416 // Request Pointer Capture from the second window before the notification from InputReader
5417 // arrives.
5418 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005419 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005420
5421 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005422 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005423
5424 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005425 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005426
5427 mSecondWindow->consumeFocusEvent(true);
5428 mSecondWindow->consumeCaptureEvent(true);
5429}
5430
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005431TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5432 // App repeatedly enables and disables capture.
5433 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5434 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5435 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5436 mFakePolicy->assertSetPointerCaptureCalled(false);
5437 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5438 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5439
5440 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5441 // first request is now stale, this should do nothing.
5442 notifyPointerCaptureChanged(firstRequest);
5443 mWindow->assertNoEvents();
5444
5445 // InputReader notifies that the second request was enabled.
5446 notifyPointerCaptureChanged(secondRequest);
5447 mWindow->consumeCaptureEvent(true);
5448}
5449
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005450class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5451protected:
5452 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005453
5454 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5455 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5456
5457 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5458 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5459
5460 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5461 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5462 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5463 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5464 MAXIMUM_OBSCURING_OPACITY);
5465
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005466 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005467 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005468 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005469
5470 sp<FakeWindowHandle> mTouchWindow;
5471
5472 virtual void SetUp() override {
5473 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005474 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005475 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5476 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5477 }
5478
5479 virtual void TearDown() override {
5480 InputDispatcherTest::TearDown();
5481 mTouchWindow.clear();
5482 }
5483
chaviw3277faf2021-05-19 16:45:23 -05005484 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5485 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005486 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005487 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005488 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005489 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005490 return window;
5491 }
5492
5493 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5494 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5495 sp<FakeWindowHandle> window =
5496 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5497 // Generate an arbitrary PID based on the UID
5498 window->setOwnerInfo(1777 + (uid % 10000), uid);
5499 return window;
5500 }
5501
5502 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5503 NotifyMotionArgs args =
5504 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5505 ADISPLAY_ID_DEFAULT, points);
5506 mDispatcher->notifyMotion(&args);
5507 }
5508};
5509
5510TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005511 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005512 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005513 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005514
5515 touch();
5516
5517 mTouchWindow->assertNoEvents();
5518}
5519
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005520TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005521 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5522 const sp<FakeWindowHandle>& w =
5523 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5524 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5525
5526 touch();
5527
5528 mTouchWindow->assertNoEvents();
5529}
5530
5531TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005532 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5533 const sp<FakeWindowHandle>& w =
5534 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5535 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5536
5537 touch();
5538
5539 w->assertNoEvents();
5540}
5541
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005542TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005543 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5544 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005545
5546 touch();
5547
5548 mTouchWindow->consumeAnyMotionDown();
5549}
5550
5551TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005552 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005553 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005554 w->setFrame(Rect(0, 0, 50, 50));
5555 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005556
5557 touch({PointF{100, 100}});
5558
5559 mTouchWindow->consumeAnyMotionDown();
5560}
5561
5562TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005563 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005564 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005565 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5566
5567 touch();
5568
5569 mTouchWindow->consumeAnyMotionDown();
5570}
5571
5572TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5573 const sp<FakeWindowHandle>& w =
5574 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5575 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005576
5577 touch();
5578
5579 mTouchWindow->consumeAnyMotionDown();
5580}
5581
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005582TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5583 const sp<FakeWindowHandle>& w =
5584 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5585 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5586
5587 touch();
5588
5589 w->assertNoEvents();
5590}
5591
5592/**
5593 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5594 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5595 * window, the occluding window will still receive ACTION_OUTSIDE event.
5596 */
5597TEST_F(InputDispatcherUntrustedTouchesTest,
5598 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5599 const sp<FakeWindowHandle>& w =
5600 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005601 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005602 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5603
5604 touch();
5605
5606 w->consumeMotionOutside();
5607}
5608
5609TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5610 const sp<FakeWindowHandle>& w =
5611 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005612 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005613 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5614
5615 touch();
5616
5617 InputEvent* event = w->consume();
5618 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5619 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5620 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5621 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5622}
5623
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005624TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005625 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005626 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5627 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005628 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5629
5630 touch();
5631
5632 mTouchWindow->consumeAnyMotionDown();
5633}
5634
5635TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5636 const sp<FakeWindowHandle>& w =
5637 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5638 MAXIMUM_OBSCURING_OPACITY);
5639 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005640
5641 touch();
5642
5643 mTouchWindow->consumeAnyMotionDown();
5644}
5645
5646TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005647 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005648 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5649 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5651
5652 touch();
5653
5654 mTouchWindow->assertNoEvents();
5655}
5656
5657TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5658 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5659 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005660 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5661 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005662 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005663 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5664 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005665 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5666
5667 touch();
5668
5669 mTouchWindow->assertNoEvents();
5670}
5671
5672TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5673 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5674 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005675 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5676 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005677 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005678 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5679 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005680 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5681
5682 touch();
5683
5684 mTouchWindow->consumeAnyMotionDown();
5685}
5686
5687TEST_F(InputDispatcherUntrustedTouchesTest,
5688 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5689 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005690 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5691 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005692 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005693 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5694 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005695 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5696
5697 touch();
5698
5699 mTouchWindow->consumeAnyMotionDown();
5700}
5701
5702TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5703 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005704 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5705 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005706 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005707 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5708 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005709 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005710
5711 touch();
5712
5713 mTouchWindow->assertNoEvents();
5714}
5715
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005716TEST_F(InputDispatcherUntrustedTouchesTest,
5717 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5718 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005719 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5720 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005721 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005722 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5723 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005724 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5725
5726 touch();
5727
5728 mTouchWindow->assertNoEvents();
5729}
5730
5731TEST_F(InputDispatcherUntrustedTouchesTest,
5732 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5733 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005734 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5735 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005736 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005737 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5738 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005739 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5740
5741 touch();
5742
5743 mTouchWindow->consumeAnyMotionDown();
5744}
5745
5746TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5747 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005748 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5749 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005750 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5751
5752 touch();
5753
5754 mTouchWindow->consumeAnyMotionDown();
5755}
5756
5757TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5758 const sp<FakeWindowHandle>& w =
5759 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5760 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5761
5762 touch();
5763
5764 mTouchWindow->consumeAnyMotionDown();
5765}
5766
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005767TEST_F(InputDispatcherUntrustedTouchesTest,
5768 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5769 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5770 const sp<FakeWindowHandle>& w =
5771 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5772 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5773
5774 touch();
5775
5776 mTouchWindow->assertNoEvents();
5777}
5778
5779TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5780 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5781 const sp<FakeWindowHandle>& w =
5782 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5783 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5784
5785 touch();
5786
5787 mTouchWindow->consumeAnyMotionDown();
5788}
5789
5790TEST_F(InputDispatcherUntrustedTouchesTest,
5791 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5792 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5793 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005794 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5795 OPACITY_ABOVE_THRESHOLD);
5796 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5797
5798 touch();
5799
5800 mTouchWindow->consumeAnyMotionDown();
5801}
5802
5803TEST_F(InputDispatcherUntrustedTouchesTest,
5804 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5805 const sp<FakeWindowHandle>& w1 =
5806 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5807 OPACITY_BELOW_THRESHOLD);
5808 const sp<FakeWindowHandle>& w2 =
5809 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5810 OPACITY_BELOW_THRESHOLD);
5811 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5812
5813 touch();
5814
5815 mTouchWindow->assertNoEvents();
5816}
5817
5818/**
5819 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5820 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5821 * (which alone would result in allowing touches) does not affect the blocking behavior.
5822 */
5823TEST_F(InputDispatcherUntrustedTouchesTest,
5824 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5825 const sp<FakeWindowHandle>& wB =
5826 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5827 OPACITY_BELOW_THRESHOLD);
5828 const sp<FakeWindowHandle>& wC =
5829 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5830 OPACITY_BELOW_THRESHOLD);
5831 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5832
5833 touch();
5834
5835 mTouchWindow->assertNoEvents();
5836}
5837
5838/**
5839 * This test is testing that a window from a different UID but with same application token doesn't
5840 * block the touch. Apps can share the application token for close UI collaboration for example.
5841 */
5842TEST_F(InputDispatcherUntrustedTouchesTest,
5843 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5844 const sp<FakeWindowHandle>& w =
5845 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5846 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005847 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5848
5849 touch();
5850
5851 mTouchWindow->consumeAnyMotionDown();
5852}
5853
arthurhungb89ccb02020-12-30 16:19:01 +08005854class InputDispatcherDragTests : public InputDispatcherTest {
5855protected:
5856 std::shared_ptr<FakeApplicationHandle> mApp;
5857 sp<FakeWindowHandle> mWindow;
5858 sp<FakeWindowHandle> mSecondWindow;
5859 sp<FakeWindowHandle> mDragWindow;
5860
5861 void SetUp() override {
5862 InputDispatcherTest::SetUp();
5863 mApp = std::make_shared<FakeApplicationHandle>();
5864 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5865 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005866 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005867
5868 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5869 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005870 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005871
5872 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5873 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5874 }
5875
5876 // Start performing drag, we will create a drag window and transfer touch to it.
5877 void performDrag() {
5878 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5879 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5880 {50, 50}))
5881 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5882
5883 // Window should receive motion event.
5884 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5885
5886 // The drag window covers the entire display
5887 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5888 mDispatcher->setInputWindows(
5889 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5890
5891 // Transfer touch focus to the drag window
5892 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5893 true /* isDragDrop */);
5894 mWindow->consumeMotionCancel();
5895 mDragWindow->consumeMotionDown();
5896 }
arthurhung6d4bed92021-03-17 11:59:33 +08005897
5898 // Start performing drag, we will create a drag window and transfer touch to it.
5899 void performStylusDrag() {
5900 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5901 injectMotionEvent(mDispatcher,
5902 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5903 AINPUT_SOURCE_STYLUS)
5904 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5905 .pointer(PointerBuilder(0,
5906 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5907 .x(50)
5908 .y(50))
5909 .build()));
5910 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5911
5912 // The drag window covers the entire display
5913 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5914 mDispatcher->setInputWindows(
5915 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5916
5917 // Transfer touch focus to the drag window
5918 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5919 true /* isDragDrop */);
5920 mWindow->consumeMotionCancel();
5921 mDragWindow->consumeMotionDown();
5922 }
arthurhungb89ccb02020-12-30 16:19:01 +08005923};
5924
5925TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5926 performDrag();
5927
5928 // Move on window.
5929 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5930 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5931 ADISPLAY_ID_DEFAULT, {50, 50}))
5932 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5933 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5934 mWindow->consumeDragEvent(false, 50, 50);
5935 mSecondWindow->assertNoEvents();
5936
5937 // Move to another window.
5938 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5939 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5940 ADISPLAY_ID_DEFAULT, {150, 50}))
5941 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5942 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5943 mWindow->consumeDragEvent(true, 150, 50);
5944 mSecondWindow->consumeDragEvent(false, 50, 50);
5945
5946 // Move back to original window.
5947 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5948 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5949 ADISPLAY_ID_DEFAULT, {50, 50}))
5950 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5951 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5952 mWindow->consumeDragEvent(false, 50, 50);
5953 mSecondWindow->consumeDragEvent(true, -50, 50);
5954
5955 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5956 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5957 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5958 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5959 mWindow->assertNoEvents();
5960 mSecondWindow->assertNoEvents();
5961}
5962
arthurhungf452d0b2021-01-06 00:19:52 +08005963TEST_F(InputDispatcherDragTests, DragAndDrop) {
5964 performDrag();
5965
5966 // Move on window.
5967 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5968 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5969 ADISPLAY_ID_DEFAULT, {50, 50}))
5970 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5971 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5972 mWindow->consumeDragEvent(false, 50, 50);
5973 mSecondWindow->assertNoEvents();
5974
5975 // Move to another window.
5976 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5977 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5978 ADISPLAY_ID_DEFAULT, {150, 50}))
5979 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5980 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5981 mWindow->consumeDragEvent(true, 150, 50);
5982 mSecondWindow->consumeDragEvent(false, 50, 50);
5983
5984 // drop to another window.
5985 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5986 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5987 {150, 50}))
5988 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5989 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5990 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5991 mWindow->assertNoEvents();
5992 mSecondWindow->assertNoEvents();
5993}
5994
arthurhung6d4bed92021-03-17 11:59:33 +08005995TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5996 performStylusDrag();
5997
5998 // Move on window and keep button pressed.
5999 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6000 injectMotionEvent(mDispatcher,
6001 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6002 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6003 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6004 .x(50)
6005 .y(50))
6006 .build()))
6007 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6008 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6009 mWindow->consumeDragEvent(false, 50, 50);
6010 mSecondWindow->assertNoEvents();
6011
6012 // Move to another window and release button, expect to drop item.
6013 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6014 injectMotionEvent(mDispatcher,
6015 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6016 .buttonState(0)
6017 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6018 .x(150)
6019 .y(50))
6020 .build()))
6021 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6022 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6023 mWindow->assertNoEvents();
6024 mSecondWindow->assertNoEvents();
6025 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6026
6027 // nothing to the window.
6028 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6029 injectMotionEvent(mDispatcher,
6030 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6031 .buttonState(0)
6032 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6033 .x(150)
6034 .y(50))
6035 .build()))
6036 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6037 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6038 mWindow->assertNoEvents();
6039 mSecondWindow->assertNoEvents();
6040}
6041
Arthur Hung6d0571e2021-04-09 20:18:16 +08006042TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6043 performDrag();
6044
6045 // Set second window invisible.
6046 mSecondWindow->setVisible(false);
6047 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6048
6049 // Move on window.
6050 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6051 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6052 ADISPLAY_ID_DEFAULT, {50, 50}))
6053 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6054 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6055 mWindow->consumeDragEvent(false, 50, 50);
6056 mSecondWindow->assertNoEvents();
6057
6058 // Move to another window.
6059 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6060 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6061 ADISPLAY_ID_DEFAULT, {150, 50}))
6062 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6063 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6064 mWindow->consumeDragEvent(true, 150, 50);
6065 mSecondWindow->assertNoEvents();
6066
6067 // drop to another window.
6068 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6069 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6070 {150, 50}))
6071 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6072 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6073 mFakePolicy->assertDropTargetEquals(nullptr);
6074 mWindow->assertNoEvents();
6075 mSecondWindow->assertNoEvents();
6076}
6077
Vishnu Nair062a8672021-09-03 16:07:44 -07006078class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6079
6080TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6081 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6082 sp<FakeWindowHandle> window =
6083 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6084 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
6085 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6086 window->setFocusable(true);
6087 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6088 setFocusedWindow(window);
6089 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6090
6091 // With the flag set, window should not get any input
6092 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6093 mDispatcher->notifyKey(&keyArgs);
6094 window->assertNoEvents();
6095
6096 NotifyMotionArgs motionArgs =
6097 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6098 ADISPLAY_ID_DEFAULT);
6099 mDispatcher->notifyMotion(&motionArgs);
6100 window->assertNoEvents();
6101
6102 // With the flag cleared, the window should get input
6103 window->setInputFeatures({});
6104 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6105
6106 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6107 mDispatcher->notifyKey(&keyArgs);
6108 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6109
6110 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6111 ADISPLAY_ID_DEFAULT);
6112 mDispatcher->notifyMotion(&motionArgs);
6113 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6114 window->assertNoEvents();
6115}
6116
6117TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6118 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6119 std::make_shared<FakeApplicationHandle>();
6120 sp<FakeWindowHandle> obscuringWindow =
6121 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6122 ADISPLAY_ID_DEFAULT);
6123 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6124 obscuringWindow->setOwnerInfo(111, 111);
6125 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6126 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6127 sp<FakeWindowHandle> window =
6128 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6129 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6130 window->setOwnerInfo(222, 222);
6131 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6132 window->setFocusable(true);
6133 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6134 setFocusedWindow(window);
6135 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6136
6137 // With the flag set, window should not get any input
6138 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6139 mDispatcher->notifyKey(&keyArgs);
6140 window->assertNoEvents();
6141
6142 NotifyMotionArgs motionArgs =
6143 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6144 ADISPLAY_ID_DEFAULT);
6145 mDispatcher->notifyMotion(&motionArgs);
6146 window->assertNoEvents();
6147
6148 // With the flag cleared, the window should get input
6149 window->setInputFeatures({});
6150 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6151
6152 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6153 mDispatcher->notifyKey(&keyArgs);
6154 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6155
6156 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6157 ADISPLAY_ID_DEFAULT);
6158 mDispatcher->notifyMotion(&motionArgs);
6159 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6160 window->assertNoEvents();
6161}
6162
6163TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6164 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6165 std::make_shared<FakeApplicationHandle>();
6166 sp<FakeWindowHandle> obscuringWindow =
6167 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6168 ADISPLAY_ID_DEFAULT);
6169 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6170 obscuringWindow->setOwnerInfo(111, 111);
6171 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6172 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6173 sp<FakeWindowHandle> window =
6174 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6175 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6176 window->setOwnerInfo(222, 222);
6177 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6178 window->setFocusable(true);
6179 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6180 setFocusedWindow(window);
6181 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6182
6183 // With the flag set, window should not get any input
6184 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6185 mDispatcher->notifyKey(&keyArgs);
6186 window->assertNoEvents();
6187
6188 NotifyMotionArgs motionArgs =
6189 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6190 ADISPLAY_ID_DEFAULT);
6191 mDispatcher->notifyMotion(&motionArgs);
6192 window->assertNoEvents();
6193
6194 // When the window is no longer obscured because it went on top, it should get input
6195 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6196
6197 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6198 mDispatcher->notifyKey(&keyArgs);
6199 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6200
6201 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6202 ADISPLAY_ID_DEFAULT);
6203 mDispatcher->notifyMotion(&motionArgs);
6204 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6205 window->assertNoEvents();
6206}
6207
Antonio Kantekf16f2832021-09-28 04:39:20 +00006208class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6209protected:
6210 std::shared_ptr<FakeApplicationHandle> mApp;
6211 sp<FakeWindowHandle> mWindow;
6212 sp<FakeWindowHandle> mSecondWindow;
6213
6214 void SetUp() override {
6215 InputDispatcherTest::SetUp();
6216
6217 mApp = std::make_shared<FakeApplicationHandle>();
6218 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6219 mWindow->setFocusable(true);
6220 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6221 mSecondWindow->setFocusable(true);
6222
6223 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6224 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6225
6226 setFocusedWindow(mWindow);
6227 mWindow->consumeFocusEvent(true);
6228 }
6229
6230 void changeAndVerifyTouchMode(bool inTouchMode) {
6231 mDispatcher->setInTouchMode(inTouchMode);
6232 mWindow->consumeTouchModeEvent(inTouchMode);
6233 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6234 }
6235};
6236
6237TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
6238 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode);
6239}
6240
6241TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
6242 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode);
6243 mWindow->assertNoEvents();
6244 mSecondWindow->assertNoEvents();
6245}
6246
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006247class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6248public:
6249 sp<FakeWindowHandle> createSpy(const Flags<WindowInfo::Flag> flags) {
6250 std::shared_ptr<FakeApplicationHandle> application =
6251 std::make_shared<FakeApplicationHandle>();
6252 std::string name = "Fake Spy ";
6253 name += std::to_string(mSpyCount++);
6254 sp<FakeWindowHandle> spy =
6255 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
6256 spy->setInputFeatures(WindowInfo::Feature::SPY);
6257 spy->addFlags(flags);
6258 return spy;
6259 }
6260
6261 sp<FakeWindowHandle> createForeground() {
6262 std::shared_ptr<FakeApplicationHandle> application =
6263 std::make_shared<FakeApplicationHandle>();
6264 sp<FakeWindowHandle> window =
6265 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
6266 window->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
6267 return window;
6268 }
6269
6270private:
6271 int mSpyCount{0};
6272};
6273
6274/**
6275 * Input injection into a display with a spy window but no foreground windows should succeed.
6276 */
6277TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
6278 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6279 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6280
6281 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6282 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6283 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6284 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6285}
6286
6287/**
6288 * Verify the order in which different input windows receive events. The touched foreground window
6289 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6290 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6291 * receive events before ones belows it.
6292 *
6293 * Here, we set up a scenario with four windows in the following Z order from the top:
6294 * spy1, spy2, window, spy3.
6295 * We then inject an event and verify that the foreground "window" receives it first, followed by
6296 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6297 * window.
6298 */
6299TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6300 auto window = createForeground();
6301 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6302 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6303 auto spy3 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6304 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6305 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6306 const size_t numChannels = channels.size();
6307
6308 base::unique_fd epollFd(epoll_create1(0 /*flags*/));
6309 if (!epollFd.ok()) {
6310 FAIL() << "Failed to create epoll fd";
6311 }
6312
6313 for (size_t i = 0; i < numChannels; i++) {
6314 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6315 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6316 FAIL() << "Failed to add fd to epoll";
6317 }
6318 }
6319
6320 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6321 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6322 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6323
6324 std::vector<size_t> eventOrder;
6325 std::vector<struct epoll_event> events(numChannels);
6326 for (;;) {
6327 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6328 (100ms).count());
6329 if (nFds < 0) {
6330 FAIL() << "Failed to call epoll_wait";
6331 }
6332 if (nFds == 0) {
6333 break; // epoll_wait timed out
6334 }
6335 for (int i = 0; i < nFds; i++) {
6336 ASSERT_EQ(EPOLLIN, events[i].events);
6337 eventOrder.push_back(events[i].data.u64);
6338 channels[i]->consumeMotionDown();
6339 }
6340 }
6341
6342 // Verify the order in which the events were received.
6343 EXPECT_EQ(3u, eventOrder.size());
6344 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6345 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6346 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6347}
6348
6349/**
6350 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6351 */
6352TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6353 auto window = createForeground();
6354 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCHABLE);
6355 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6356
6357 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6358 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6359 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6360 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6361 spy->assertNoEvents();
6362}
6363
6364/**
6365 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6366 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6367 * to the window.
6368 */
6369TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6370 auto window = createForeground();
6371 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6372 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6373 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6374
6375 // Inject an event outside the spy window's touchable region.
6376 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6377 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6378 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6379 window->consumeMotionDown();
6380 spy->assertNoEvents();
6381 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6382 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6383 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6384 window->consumeMotionUp();
6385 spy->assertNoEvents();
6386
6387 // Inject an event inside the spy window's touchable region.
6388 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6389 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6390 {5, 10}))
6391 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6392 window->consumeMotionDown();
6393 spy->consumeMotionDown();
6394}
6395
6396/**
6397 * A spy window that is a modal window will receive gestures outside of its frame and touchable
6398 * region.
6399 */
6400TEST_F(InputDispatcherSpyWindowTest, ModalWindow) {
6401 auto window = createForeground();
6402 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6403 // This spy window does not have the NOT_TOUCH_MODAL flag set.
6404 spy->setFrame(Rect{0, 0, 20, 20});
6405 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6406
6407 // Inject an event outside the spy window's frame and touchable region.
6408 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6409 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6410 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6411 window->consumeMotionDown();
6412 spy->consumeMotionDown();
6413}
6414
6415/**
6416 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
6417 * flag.
6418 */
6419TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6420 auto window = createForeground();
6421 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
6422 spy->setFrame(Rect{0, 0, 20, 20});
6423 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6424
6425 // Inject an event outside the spy window's frame and touchable region.
6426 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6427 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6428 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6429 window->consumeMotionDown();
6430 spy->consumeMotionOutside();
6431}
6432
6433/**
6434 * When configured to block untrusted touches, events will not be dispatched to windows below a spy
6435 * window if it is not a trusted overly.
6436 */
6437TEST_F(InputDispatcherSpyWindowTest, BlockUntrustedTouches) {
6438 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
6439
6440 auto window = createForeground();
6441 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6442 window->setOwnerInfo(111, 111);
6443 spy->setOwnerInfo(222, 222);
6444 spy->setTouchOcclusionMode(TouchOcclusionMode::BLOCK_UNTRUSTED);
6445 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6446
6447 // Inject an event outside the spy window's frame and touchable region.
6448 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6449 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6450 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6451 spy->consumeMotionDown();
6452 window->assertNoEvents();
6453}
6454
6455/**
6456 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6457 * any other windows - including other spy windows - will also be cancelled.
6458 */
6459TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6460 auto window = createForeground();
6461 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6462 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6463 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6464
6465 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6466 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6467 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6468 window->consumeMotionDown();
6469 spy1->consumeMotionDown();
6470 spy2->consumeMotionDown();
6471
6472 // Pilfer pointers from the second spy window.
6473 mDispatcher->pilferPointers(spy2->getToken());
6474 spy2->assertNoEvents();
6475 spy1->consumeMotionCancel();
6476 window->consumeMotionCancel();
6477
6478 // The rest of the gesture should only be sent to the second spy window.
6479 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6480 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6481 ADISPLAY_ID_DEFAULT))
6482 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6483 spy2->consumeMotionMove();
6484 spy1->assertNoEvents();
6485 window->assertNoEvents();
6486}
6487
6488/**
6489 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6490 * pointers that are down within its bounds.
6491 */
6492TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6493 auto windowLeft = createForeground();
6494 windowLeft->setFrame({0, 0, 100, 200});
6495 auto windowRight = createForeground();
6496 windowRight->setFrame({100, 0, 200, 200});
6497 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6498 spy->setFrame({0, 0, 200, 200});
6499 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6500
6501 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6502 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6503 {50, 50}))
6504 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6505 windowLeft->consumeMotionDown();
6506 spy->consumeMotionDown();
6507
6508 const MotionEvent secondFingerDownEvent =
6509 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6510 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6511 AINPUT_SOURCE_TOUCHSCREEN)
6512 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6513 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6514 .pointer(
6515 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6516 .build();
6517 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6518 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6519 InputEventInjectionSync::WAIT_FOR_RESULT))
6520 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6521 windowRight->consumeMotionDown();
6522 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6523}
6524
6525/**
6526 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6527 * the spy should receive the second pointer with ACTION_DOWN.
6528 */
6529TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6530 auto window = createForeground();
6531 window->setFrame({0, 0, 200, 200});
6532 auto spyRight = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6533 spyRight->setFrame({100, 0, 200, 200});
6534 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6535
6536 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6537 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6538 {50, 50}))
6539 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6540 window->consumeMotionDown();
6541 spyRight->assertNoEvents();
6542
6543 const MotionEvent secondFingerDownEvent =
6544 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6545 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6546 AINPUT_SOURCE_TOUCHSCREEN)
6547 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6548 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6549 .pointer(
6550 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6551 .build();
6552 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6553 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6554 InputEventInjectionSync::WAIT_FOR_RESULT))
6555 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6556 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6557 spyRight->consumeMotionDown();
6558}
6559
Garfield Tane84e6f92019-08-29 17:28:41 -07006560} // namespace android::inputdispatcher