blob: b2d0fb841c080efaa328f79cc62b527b195b44b9 [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;
Prabir Pradhand65552b2021-10-07 11:23:50 -07001006 mInfo.trustedOverlay = false;
chaviwd1c23182019-12-20 18:44:56 -08001007 }
1008
Arthur Hungabbb9d82021-09-01 14:52:30 +00001009 sp<FakeWindowHandle> clone(
1010 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001011 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001012 sp<FakeWindowHandle> handle =
1013 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1014 displayId, mInfo.token);
1015 return handle;
1016 }
1017
Vishnu Nair47074b82020-08-14 11:54:47 -07001018 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -08001019
Vishnu Nair958da932020-08-21 17:12:37 -07001020 void setVisible(bool visible) { mInfo.visible = visible; }
1021
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001022 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001023 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001024 }
1025
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001026 void setPaused(bool paused) { mInfo.paused = paused; }
1027
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001028 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1029
chaviw3277faf2021-05-19 16:45:23 -05001030 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001031
Bernardo Rufino7393d172021-02-26 13:56:11 +00001032 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1033
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001034 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001035 mInfo.frameLeft = frame.left;
1036 mInfo.frameTop = frame.top;
1037 mInfo.frameRight = frame.right;
1038 mInfo.frameBottom = frame.bottom;
1039 mInfo.touchableRegion.clear();
1040 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001041
1042 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1043 ui::Transform translate;
1044 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1045 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001046 }
1047
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001048 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1049
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001050 void setType(WindowInfo::Type type) { mInfo.type = type; }
1051
1052 void setHasWallpaper(bool hasWallpaper) { mInfo.hasWallpaper = hasWallpaper; }
1053
chaviw3277faf2021-05-19 16:45:23 -05001054 void addFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags |= flags; }
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00001055
chaviw3277faf2021-05-19 16:45:23 -05001056 void setFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -08001057
Prabir Pradhand65552b2021-10-07 11:23:50 -07001058 void setInputFeatures(Flags<WindowInfo::Feature> features) { mInfo.inputFeatures = features; }
1059
1060 void setTrustedOverlay(bool trustedOverlay) { mInfo.trustedOverlay = trustedOverlay; }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001061
chaviw9eaa22c2020-07-01 16:21:27 -07001062 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1063 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1064 }
1065
1066 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001067
yunho.shinf4a80b82020-11-16 21:13:57 +09001068 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1069
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001070 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1071 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1072 expectedFlags);
1073 }
1074
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001075 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1076 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1077 }
1078
Svet Ganov5d3bc372020-01-26 23:11:07 -08001079 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001080 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001081 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1082 expectedFlags);
1083 }
1084
1085 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001086 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001087 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1088 expectedFlags);
1089 }
1090
1091 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001092 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001093 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1094 }
1095
1096 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1097 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001098 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1099 expectedFlags);
1100 }
1101
Svet Ganov5d3bc372020-01-26 23:11:07 -08001102 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001103 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1104 int32_t expectedFlags = 0) {
1105 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1106 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001107 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1108 }
1109
1110 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001111 int32_t expectedFlags = 0) {
1112 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1113 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001114 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1115 }
1116
1117 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001118 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001119 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1120 expectedFlags);
1121 }
1122
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001123 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1124 int32_t expectedFlags = 0) {
1125 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1126 expectedFlags);
1127 }
1128
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001129 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1130 ASSERT_NE(mInputReceiver, nullptr)
1131 << "Cannot consume events from a window with no receiver";
1132 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1133 }
1134
Prabir Pradhan99987712020-11-10 18:43:05 -08001135 void consumeCaptureEvent(bool hasCapture) {
1136 ASSERT_NE(mInputReceiver, nullptr)
1137 << "Cannot consume events from a window with no receiver";
1138 mInputReceiver->consumeCaptureEvent(hasCapture);
1139 }
1140
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001141 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1142 std::optional<int32_t> expectedDisplayId,
1143 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001144 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1145 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1146 expectedFlags);
1147 }
1148
arthurhungb89ccb02020-12-30 16:19:01 +08001149 void consumeDragEvent(bool isExiting, float x, float y) {
1150 mInputReceiver->consumeDragEvent(isExiting, x, y);
1151 }
1152
Antonio Kantekf16f2832021-09-28 04:39:20 +00001153 void consumeTouchModeEvent(bool inTouchMode) {
1154 ASSERT_NE(mInputReceiver, nullptr)
1155 << "Cannot consume events from a window with no receiver";
1156 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1157 }
1158
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001159 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001160 if (mInputReceiver == nullptr) {
1161 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1162 return std::nullopt;
1163 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001164 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001165 }
1166
1167 void finishEvent(uint32_t sequenceNum) {
1168 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1169 mInputReceiver->finishEvent(sequenceNum);
1170 }
1171
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001172 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1173 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1174 mInputReceiver->sendTimeline(inputEventId, timeline);
1175 }
1176
chaviwaf87b3e2019-10-01 16:59:28 -07001177 InputEvent* consume() {
1178 if (mInputReceiver == nullptr) {
1179 return nullptr;
1180 }
1181 return mInputReceiver->consume();
1182 }
1183
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001184 MotionEvent* consumeMotion() {
1185 InputEvent* event = consume();
1186 if (event == nullptr) {
1187 ADD_FAILURE() << "Consume failed : no event";
1188 return nullptr;
1189 }
1190 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1191 ADD_FAILURE() << "Instead of motion event, got "
1192 << inputEventTypeToString(event->getType());
1193 return nullptr;
1194 }
1195 return static_cast<MotionEvent*>(event);
1196 }
1197
Arthur Hungb92218b2018-08-14 12:00:21 +08001198 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001199 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001200 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001201 return; // Can't receive events if the window does not have input channel
1202 }
1203 ASSERT_NE(nullptr, mInputReceiver)
1204 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001205 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001206 }
1207
chaviwaf87b3e2019-10-01 16:59:28 -07001208 sp<IBinder> getToken() { return mInfo.token; }
1209
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001210 const std::string& getName() { return mName; }
1211
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001212 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1213 mInfo.ownerPid = ownerPid;
1214 mInfo.ownerUid = ownerUid;
1215 }
1216
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001217 void destroyReceiver() { mInputReceiver = nullptr; }
1218
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001219 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1220
chaviwd1c23182019-12-20 18:44:56 -08001221private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001222 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001223 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001224 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001225};
1226
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001227std::atomic<int32_t> FakeWindowHandle::sId{1};
1228
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001229static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001230 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001231 int32_t displayId = ADISPLAY_ID_NONE,
1232 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001233 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1234 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001235 KeyEvent event;
1236 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1237
1238 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001239 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001240 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1241 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001242
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001243 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1244 if (!allowKeyRepeat) {
1245 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1246 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001247 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001248 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001249 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001250}
1251
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001252static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001253 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001254 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1255}
1256
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001257// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1258// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1259// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001260static InputEventInjectionResult injectKeyDownNoRepeat(
1261 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001262 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1263 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1264 /* allowKeyRepeat */ false);
1265}
1266
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001267static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001268 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001269 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1270}
1271
Garfield Tandf26e862020-07-01 20:18:19 -07001272class PointerBuilder {
1273public:
1274 PointerBuilder(int32_t id, int32_t toolType) {
1275 mProperties.clear();
1276 mProperties.id = id;
1277 mProperties.toolType = toolType;
1278 mCoords.clear();
1279 }
1280
1281 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1282
1283 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1284
1285 PointerBuilder& axis(int32_t axis, float value) {
1286 mCoords.setAxisValue(axis, value);
1287 return *this;
1288 }
1289
1290 PointerProperties buildProperties() const { return mProperties; }
1291
1292 PointerCoords buildCoords() const { return mCoords; }
1293
1294private:
1295 PointerProperties mProperties;
1296 PointerCoords mCoords;
1297};
1298
1299class MotionEventBuilder {
1300public:
1301 MotionEventBuilder(int32_t action, int32_t source) {
1302 mAction = action;
1303 mSource = source;
1304 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1305 }
1306
1307 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1308 mEventTime = eventTime;
1309 return *this;
1310 }
1311
1312 MotionEventBuilder& displayId(int32_t displayId) {
1313 mDisplayId = displayId;
1314 return *this;
1315 }
1316
1317 MotionEventBuilder& actionButton(int32_t actionButton) {
1318 mActionButton = actionButton;
1319 return *this;
1320 }
1321
arthurhung6d4bed92021-03-17 11:59:33 +08001322 MotionEventBuilder& buttonState(int32_t buttonState) {
1323 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001324 return *this;
1325 }
1326
1327 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1328 mRawXCursorPosition = rawXCursorPosition;
1329 return *this;
1330 }
1331
1332 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1333 mRawYCursorPosition = rawYCursorPosition;
1334 return *this;
1335 }
1336
1337 MotionEventBuilder& pointer(PointerBuilder pointer) {
1338 mPointers.push_back(pointer);
1339 return *this;
1340 }
1341
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001342 MotionEventBuilder& addFlag(uint32_t flags) {
1343 mFlags |= flags;
1344 return *this;
1345 }
1346
Garfield Tandf26e862020-07-01 20:18:19 -07001347 MotionEvent build() {
1348 std::vector<PointerProperties> pointerProperties;
1349 std::vector<PointerCoords> pointerCoords;
1350 for (const PointerBuilder& pointer : mPointers) {
1351 pointerProperties.push_back(pointer.buildProperties());
1352 pointerCoords.push_back(pointer.buildCoords());
1353 }
1354
1355 // Set mouse cursor position for the most common cases to avoid boilerplate.
1356 if (mSource == AINPUT_SOURCE_MOUSE &&
1357 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1358 mPointers.size() == 1) {
1359 mRawXCursorPosition = pointerCoords[0].getX();
1360 mRawYCursorPosition = pointerCoords[0].getY();
1361 }
1362
1363 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001364 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001365 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001366 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001367 mButtonState, MotionClassification::NONE, identityTransform,
1368 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001369 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1370 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001371
1372 return event;
1373 }
1374
1375private:
1376 int32_t mAction;
1377 int32_t mSource;
1378 nsecs_t mEventTime;
1379 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1380 int32_t mActionButton{0};
1381 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001382 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001383 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1384 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1385
1386 std::vector<PointerBuilder> mPointers;
1387};
1388
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001389static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001390 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001391 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001392 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001393 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1394 injectionTimeout,
1395 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1396}
1397
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001398static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001399 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001400 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001401 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001402 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1403 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001404 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001405 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001406 MotionEvent event = MotionEventBuilder(action, source)
1407 .displayId(displayId)
1408 .eventTime(eventTime)
1409 .rawXCursorPosition(cursorPosition.x)
1410 .rawYCursorPosition(cursorPosition.y)
1411 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1412 .x(position.x)
1413 .y(position.y))
1414 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001415
1416 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001417 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001418}
1419
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001420static InputEventInjectionResult injectMotionDown(
1421 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1422 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001423 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001424}
1425
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001426static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001427 int32_t source, int32_t displayId,
1428 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001429 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001430}
1431
Jackal Guof9696682018-10-05 12:23:23 +08001432static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1433 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1434 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001435 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1436 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1437 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001438
1439 return args;
1440}
1441
chaviwd1c23182019-12-20 18:44:56 -08001442static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1443 const std::vector<PointF>& points) {
1444 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001445 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1446 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1447 }
1448
chaviwd1c23182019-12-20 18:44:56 -08001449 PointerProperties pointerProperties[pointerCount];
1450 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001451
chaviwd1c23182019-12-20 18:44:56 -08001452 for (size_t i = 0; i < pointerCount; i++) {
1453 pointerProperties[i].clear();
1454 pointerProperties[i].id = i;
1455 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001456
chaviwd1c23182019-12-20 18:44:56 -08001457 pointerCoords[i].clear();
1458 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1459 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1460 }
Jackal Guof9696682018-10-05 12:23:23 +08001461
1462 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1463 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001464 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001465 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1466 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001467 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1468 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001469 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1470 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001471
1472 return args;
1473}
1474
chaviwd1c23182019-12-20 18:44:56 -08001475static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1476 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1477}
1478
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001479static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1480 const PointerCaptureRequest& request) {
1481 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001482}
1483
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001484/**
1485 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1486 * broken channel.
1487 */
1488TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1489 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1490 sp<FakeWindowHandle> window =
1491 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1492 ADISPLAY_ID_DEFAULT);
1493
1494 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1495
1496 // Window closes its channel, but the window remains.
1497 window->destroyReceiver();
1498 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1499}
1500
Arthur Hungb92218b2018-08-14 12:00:21 +08001501TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001502 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001503 sp<FakeWindowHandle> window =
1504 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001505
Arthur Hung72d8dc32020-03-28 00:48:39 +00001506 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001507 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1508 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1509 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001510
1511 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001512 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001513}
1514
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001515TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1516 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1517 sp<FakeWindowHandle> window =
1518 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1519
1520 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1521 // Inject a MotionEvent to an unknown display.
1522 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1523 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1524 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1525
1526 // Window should receive motion event.
1527 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1528}
1529
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001530/**
1531 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1532 * To ensure that window receives only events that were directly inside of it, add
1533 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1534 * when finding touched windows.
1535 * This test serves as a sanity check for the next test, where setInputWindows is
1536 * called twice.
1537 */
1538TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001539 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001540 sp<FakeWindowHandle> window =
1541 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1542 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001543 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001544
1545 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001546 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001547 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1548 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001549 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001550
1551 // Window should receive motion event.
1552 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1553}
1554
1555/**
1556 * Calling setInputWindows twice, with the same info, should not cause any issues.
1557 * To ensure that window receives only events that were directly inside of it, add
1558 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1559 * when finding touched windows.
1560 */
1561TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001562 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001563 sp<FakeWindowHandle> window =
1564 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1565 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001566 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001567
1568 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1569 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001570 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001571 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1572 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001573 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001574
1575 // Window should receive motion event.
1576 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1577}
1578
Arthur Hungb92218b2018-08-14 12:00:21 +08001579// The foreground window should receive the first touch down event.
1580TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001581 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001582 sp<FakeWindowHandle> windowTop =
1583 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1584 sp<FakeWindowHandle> windowSecond =
1585 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001586
Arthur Hung72d8dc32020-03-28 00:48:39 +00001587 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001588 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1589 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1590 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001591
1592 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001593 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001594 windowSecond->assertNoEvents();
1595}
1596
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001597/**
1598 * Two windows: A top window, and a wallpaper behind the window.
1599 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1600 * gets ACTION_CANCEL.
1601 * 1. foregroundWindow <-- has wallpaper (hasWallpaper=true)
1602 * 2. wallpaperWindow <-- is wallpaper (type=InputWindowInfo::Type::WALLPAPER)
1603 */
1604TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1605 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1606 sp<FakeWindowHandle> foregroundWindow =
1607 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1608 foregroundWindow->setHasWallpaper(true);
1609 sp<FakeWindowHandle> wallpaperWindow =
1610 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1611 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1612 constexpr int expectedWallpaperFlags =
1613 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1614
1615 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1616 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1617 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1618 {100, 200}))
1619 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1620
1621 // Both foreground window and its wallpaper should receive the touch down
1622 foregroundWindow->consumeMotionDown();
1623 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1624
1625 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1626 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1627 ADISPLAY_ID_DEFAULT, {110, 200}))
1628 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1629
1630 foregroundWindow->consumeMotionMove();
1631 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1632
1633 // Now the foreground window goes away, but the wallpaper stays
1634 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1635 foregroundWindow->consumeMotionCancel();
1636 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1637 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1638}
1639
1640/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001641 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1642 * with the following differences:
1643 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1644 * clean up the connection.
1645 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1646 * Ensure that there's no crash in the dispatcher.
1647 */
1648TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1649 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1650 sp<FakeWindowHandle> foregroundWindow =
1651 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1652 foregroundWindow->setHasWallpaper(true);
1653 sp<FakeWindowHandle> wallpaperWindow =
1654 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1655 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1656 constexpr int expectedWallpaperFlags =
1657 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1658
1659 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1660 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1661 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1662 {100, 200}))
1663 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1664
1665 // Both foreground window and its wallpaper should receive the touch down
1666 foregroundWindow->consumeMotionDown();
1667 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1668
1669 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1670 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1671 ADISPLAY_ID_DEFAULT, {110, 200}))
1672 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1673
1674 foregroundWindow->consumeMotionMove();
1675 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1676
1677 // Wallpaper closes its channel, but the window remains.
1678 wallpaperWindow->destroyReceiver();
1679 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1680
1681 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1682 // is no longer valid.
1683 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1684 foregroundWindow->consumeMotionCancel();
1685}
1686
1687/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001688 * A single window that receives touch (on top), and a wallpaper window underneath it.
1689 * The top window gets a multitouch gesture.
1690 * Ensure that wallpaper gets the same gesture.
1691 */
1692TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1693 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1694 sp<FakeWindowHandle> window =
1695 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1696 window->setHasWallpaper(true);
1697
1698 sp<FakeWindowHandle> wallpaperWindow =
1699 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1700 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1701 constexpr int expectedWallpaperFlags =
1702 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1703
1704 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1705
1706 // Touch down on top window
1707 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1708 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1709 {100, 100}))
1710 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1711
1712 // Both top window and its wallpaper should receive the touch down
1713 window->consumeMotionDown();
1714 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1715
1716 // Second finger down on the top window
1717 const MotionEvent secondFingerDownEvent =
1718 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1719 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1720 AINPUT_SOURCE_TOUCHSCREEN)
1721 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1722 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1723 .x(100)
1724 .y(100))
1725 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1726 .x(150)
1727 .y(150))
1728 .build();
1729 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1730 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1731 InputEventInjectionSync::WAIT_FOR_RESULT))
1732 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1733
1734 window->consumeMotionPointerDown(1 /* pointerIndex */);
1735 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1736 expectedWallpaperFlags);
1737 window->assertNoEvents();
1738 wallpaperWindow->assertNoEvents();
1739}
1740
1741/**
1742 * Two windows: a window on the left and window on the right.
1743 * A third window, wallpaper, is behind both windows, and spans both top windows.
1744 * The first touch down goes to the left window. A second pointer touches down on the right window.
1745 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1746 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1747 * ACTION_POINTER_DOWN(1).
1748 */
1749TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1750 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1751 sp<FakeWindowHandle> leftWindow =
1752 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1753 leftWindow->setFrame(Rect(0, 0, 200, 200));
1754 leftWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1755 leftWindow->setHasWallpaper(true);
1756
1757 sp<FakeWindowHandle> rightWindow =
1758 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1759 rightWindow->setFrame(Rect(200, 0, 400, 200));
1760 rightWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1761 rightWindow->setHasWallpaper(true);
1762
1763 sp<FakeWindowHandle> wallpaperWindow =
1764 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1765 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
1766 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1767 constexpr int expectedWallpaperFlags =
1768 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1769
1770 mDispatcher->setInputWindows(
1771 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1772
1773 // Touch down on left window
1774 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1775 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1776 {100, 100}))
1777 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1778
1779 // Both foreground window and its wallpaper should receive the touch down
1780 leftWindow->consumeMotionDown();
1781 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1782
1783 // Second finger down on the right window
1784 const MotionEvent secondFingerDownEvent =
1785 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1786 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1787 AINPUT_SOURCE_TOUCHSCREEN)
1788 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1789 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1790 .x(100)
1791 .y(100))
1792 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1793 .x(300)
1794 .y(100))
1795 .build();
1796 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1797 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1798 InputEventInjectionSync::WAIT_FOR_RESULT))
1799 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1800
1801 leftWindow->consumeMotionMove();
1802 // Since the touch is split, right window gets ACTION_DOWN
1803 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1804 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1805 expectedWallpaperFlags);
1806
1807 // Now, leftWindow, which received the first finger, disappears.
1808 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1809 leftWindow->consumeMotionCancel();
1810 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1811 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1812
1813 // The pointer that's still down on the right window moves, and goes to the right window only.
1814 // As far as the dispatcher's concerned though, both pointers are still present.
1815 const MotionEvent secondFingerMoveEvent =
1816 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1817 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1818 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1819 .x(100)
1820 .y(100))
1821 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1822 .x(310)
1823 .y(110))
1824 .build();
1825 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1826 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1827 InputEventInjectionSync::WAIT_FOR_RESULT));
1828 rightWindow->consumeMotionMove();
1829
1830 leftWindow->assertNoEvents();
1831 rightWindow->assertNoEvents();
1832 wallpaperWindow->assertNoEvents();
1833}
1834
Garfield Tandf26e862020-07-01 20:18:19 -07001835TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001836 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001837 sp<FakeWindowHandle> windowLeft =
1838 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1839 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001840 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001841 sp<FakeWindowHandle> windowRight =
1842 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1843 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001844 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001845
1846 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1847
1848 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1849
1850 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001851 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001852 injectMotionEvent(mDispatcher,
1853 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1854 AINPUT_SOURCE_MOUSE)
1855 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1856 .x(900)
1857 .y(400))
1858 .build()));
1859 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1860 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1861 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1862 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1863
1864 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001865 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001866 injectMotionEvent(mDispatcher,
1867 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1868 AINPUT_SOURCE_MOUSE)
1869 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1870 .x(300)
1871 .y(400))
1872 .build()));
1873 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1874 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1875 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1876 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1877 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1878 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1879
1880 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001881 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001882 injectMotionEvent(mDispatcher,
1883 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1884 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1885 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1886 .x(300)
1887 .y(400))
1888 .build()));
1889 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1890
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001891 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001892 injectMotionEvent(mDispatcher,
1893 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1894 AINPUT_SOURCE_MOUSE)
1895 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1896 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1897 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1898 .x(300)
1899 .y(400))
1900 .build()));
1901 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1902 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1903
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001904 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001905 injectMotionEvent(mDispatcher,
1906 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1907 AINPUT_SOURCE_MOUSE)
1908 .buttonState(0)
1909 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1910 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1911 .x(300)
1912 .y(400))
1913 .build()));
1914 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1915 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1916
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001917 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001918 injectMotionEvent(mDispatcher,
1919 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1920 .buttonState(0)
1921 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1922 .x(300)
1923 .y(400))
1924 .build()));
1925 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1926
1927 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001928 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001929 injectMotionEvent(mDispatcher,
1930 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1931 AINPUT_SOURCE_MOUSE)
1932 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1933 .x(900)
1934 .y(400))
1935 .build()));
1936 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1937 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1938 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1939 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1940 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1941 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1942}
1943
1944// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1945// directly in this test.
1946TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001947 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001948 sp<FakeWindowHandle> window =
1949 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1950 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001951 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001952
1953 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1954
1955 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1956
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001957 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001958 injectMotionEvent(mDispatcher,
1959 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1960 AINPUT_SOURCE_MOUSE)
1961 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1962 .x(300)
1963 .y(400))
1964 .build()));
1965 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1966 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1967
1968 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001970 injectMotionEvent(mDispatcher,
1971 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1972 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1973 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1974 .x(300)
1975 .y(400))
1976 .build()));
1977 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1978
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001979 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001980 injectMotionEvent(mDispatcher,
1981 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1982 AINPUT_SOURCE_MOUSE)
1983 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1984 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1985 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1986 .x(300)
1987 .y(400))
1988 .build()));
1989 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1990 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1991
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001992 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001993 injectMotionEvent(mDispatcher,
1994 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1995 AINPUT_SOURCE_MOUSE)
1996 .buttonState(0)
1997 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1998 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1999 .x(300)
2000 .y(400))
2001 .build()));
2002 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2003 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2004
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002005 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002006 injectMotionEvent(mDispatcher,
2007 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2008 .buttonState(0)
2009 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2010 .x(300)
2011 .y(400))
2012 .build()));
2013 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2014
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002015 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002016 injectMotionEvent(mDispatcher,
2017 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2018 AINPUT_SOURCE_MOUSE)
2019 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2020 .x(300)
2021 .y(400))
2022 .build()));
2023 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2024 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2025}
2026
Garfield Tan00f511d2019-06-12 16:55:40 -07002027TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002028 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002029
2030 sp<FakeWindowHandle> windowLeft =
2031 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2032 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002033 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002034 sp<FakeWindowHandle> windowRight =
2035 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2036 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05002037 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002038
2039 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2040
Arthur Hung72d8dc32020-03-28 00:48:39 +00002041 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002042
2043 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2044 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002045 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002046 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002047 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002048 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002049 windowRight->assertNoEvents();
2050}
2051
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002052TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002053 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002054 sp<FakeWindowHandle> window =
2055 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002056 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002057
Arthur Hung72d8dc32020-03-28 00:48:39 +00002058 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002059 setFocusedWindow(window);
2060
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002061 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002062
2063 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2064 mDispatcher->notifyKey(&keyArgs);
2065
2066 // Window should receive key down event.
2067 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2068
2069 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2070 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002071 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002072 mDispatcher->notifyDeviceReset(&args);
2073 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2074 AKEY_EVENT_FLAG_CANCELED);
2075}
2076
2077TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002078 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002079 sp<FakeWindowHandle> window =
2080 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2081
Arthur Hung72d8dc32020-03-28 00:48:39 +00002082 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002083
2084 NotifyMotionArgs motionArgs =
2085 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2086 ADISPLAY_ID_DEFAULT);
2087 mDispatcher->notifyMotion(&motionArgs);
2088
2089 // Window should receive motion down event.
2090 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2091
2092 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2093 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002094 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002095 mDispatcher->notifyDeviceReset(&args);
2096 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2097 0 /*expectedFlags*/);
2098}
2099
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002100/**
2101 * Ensure the correct coordinate spaces are used by InputDispatcher.
2102 *
2103 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2104 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2105 * space.
2106 */
2107class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2108public:
2109 void SetUp() override {
2110 InputDispatcherTest::SetUp();
2111 mDisplayInfos.clear();
2112 mWindowInfos.clear();
2113 }
2114
2115 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2116 gui::DisplayInfo info;
2117 info.displayId = displayId;
2118 info.transform = transform;
2119 mDisplayInfos.push_back(std::move(info));
2120 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2121 }
2122
2123 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2124 mWindowInfos.push_back(*windowHandle->getInfo());
2125 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2126 }
2127
2128 // Set up a test scenario where the display has a scaled projection and there are two windows
2129 // on the display.
2130 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2131 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2132 // respectively.
2133 ui::Transform displayTransform;
2134 displayTransform.set(2, 0, 0, 4);
2135 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2136
2137 std::shared_ptr<FakeApplicationHandle> application =
2138 std::make_shared<FakeApplicationHandle>();
2139
2140 // Add two windows to the display. Their frames are represented in the display space.
2141 sp<FakeWindowHandle> firstWindow =
2142 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2143 firstWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2144 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2145 addWindow(firstWindow);
2146
2147 sp<FakeWindowHandle> secondWindow =
2148 new FakeWindowHandle(application, mDispatcher, "Second Window",
2149 ADISPLAY_ID_DEFAULT);
2150 secondWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2151 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2152 addWindow(secondWindow);
2153 return {std::move(firstWindow), std::move(secondWindow)};
2154 }
2155
2156private:
2157 std::vector<gui::DisplayInfo> mDisplayInfos;
2158 std::vector<gui::WindowInfo> mWindowInfos;
2159};
2160
2161TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2162 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2163 // Send down to the first window. The point is represented in the display space. The point is
2164 // selected so that if the hit test was done with the transform applied to it, then it would
2165 // end up in the incorrect window.
2166 NotifyMotionArgs downMotionArgs =
2167 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2168 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2169 mDispatcher->notifyMotion(&downMotionArgs);
2170
2171 firstWindow->consumeMotionDown();
2172 secondWindow->assertNoEvents();
2173}
2174
2175// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2176// the event should be treated as being in the logical display space.
2177TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2178 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2179 // Send down to the first window. The point is represented in the logical display space. The
2180 // point is selected so that if the hit test was done in logical display space, then it would
2181 // end up in the incorrect window.
2182 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2183 PointF{75 * 2, 55 * 4});
2184
2185 firstWindow->consumeMotionDown();
2186 secondWindow->assertNoEvents();
2187}
2188
2189TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2190 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2191
2192 // Send down to the second window.
2193 NotifyMotionArgs downMotionArgs =
2194 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2195 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2196 mDispatcher->notifyMotion(&downMotionArgs);
2197
2198 firstWindow->assertNoEvents();
2199 const MotionEvent* event = secondWindow->consumeMotion();
2200 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2201
2202 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2203 EXPECT_EQ(300, event->getRawX(0));
2204 EXPECT_EQ(880, event->getRawY(0));
2205
2206 // Ensure that the x and y values are in the window's coordinate space.
2207 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2208 // the logical display space. This will be the origin of the window space.
2209 EXPECT_EQ(100, event->getX(0));
2210 EXPECT_EQ(80, event->getY(0));
2211}
2212
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002213using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2214 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002215
2216class TransferTouchFixture : public InputDispatcherTest,
2217 public ::testing::WithParamInterface<TransferFunction> {};
2218
2219TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002220 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002221
2222 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002223 sp<FakeWindowHandle> firstWindow =
2224 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2225 sp<FakeWindowHandle> secondWindow =
2226 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002227
2228 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002229 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002230
2231 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002232 NotifyMotionArgs downMotionArgs =
2233 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2234 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002235 mDispatcher->notifyMotion(&downMotionArgs);
2236 // Only the first window should get the down event
2237 firstWindow->consumeMotionDown();
2238 secondWindow->assertNoEvents();
2239
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002240 // Transfer touch to the second window
2241 TransferFunction f = GetParam();
2242 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2243 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002244 // The first window gets cancel and the second gets down
2245 firstWindow->consumeMotionCancel();
2246 secondWindow->consumeMotionDown();
2247
2248 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002249 NotifyMotionArgs upMotionArgs =
2250 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2251 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002252 mDispatcher->notifyMotion(&upMotionArgs);
2253 // The first window gets no events and the second gets up
2254 firstWindow->assertNoEvents();
2255 secondWindow->consumeMotionUp();
2256}
2257
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002258TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002259 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002260
2261 PointF touchPoint = {10, 10};
2262
2263 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002264 sp<FakeWindowHandle> firstWindow =
2265 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2266 sp<FakeWindowHandle> secondWindow =
2267 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002268
2269 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002270 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002271
2272 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002273 NotifyMotionArgs downMotionArgs =
2274 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2275 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002276 mDispatcher->notifyMotion(&downMotionArgs);
2277 // Only the first window should get the down event
2278 firstWindow->consumeMotionDown();
2279 secondWindow->assertNoEvents();
2280
2281 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002282 NotifyMotionArgs pointerDownMotionArgs =
2283 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2284 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2285 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2286 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002287 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2288 // Only the first window should get the pointer down event
2289 firstWindow->consumeMotionPointerDown(1);
2290 secondWindow->assertNoEvents();
2291
2292 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002293 TransferFunction f = GetParam();
2294 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2295 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002296 // The first window gets cancel and the second gets down and pointer down
2297 firstWindow->consumeMotionCancel();
2298 secondWindow->consumeMotionDown();
2299 secondWindow->consumeMotionPointerDown(1);
2300
2301 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002302 NotifyMotionArgs pointerUpMotionArgs =
2303 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2304 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2305 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2306 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002307 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2308 // The first window gets nothing and the second gets pointer up
2309 firstWindow->assertNoEvents();
2310 secondWindow->consumeMotionPointerUp(1);
2311
2312 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002313 NotifyMotionArgs upMotionArgs =
2314 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2315 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002316 mDispatcher->notifyMotion(&upMotionArgs);
2317 // The first window gets nothing and the second gets up
2318 firstWindow->assertNoEvents();
2319 secondWindow->consumeMotionUp();
2320}
2321
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002322// For the cases of single pointer touch and two pointers non-split touch, the api's
2323// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2324// for the case where there are multiple pointers split across several windows.
2325INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2326 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002327 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2328 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002329 return dispatcher->transferTouch(destChannelToken);
2330 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002331 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2332 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002333 return dispatcher->transferTouchFocus(from, to,
2334 false /*isDragAndDrop*/);
2335 }));
2336
Svet Ganov5d3bc372020-01-26 23:11:07 -08002337TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002338 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002339
2340 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002341 sp<FakeWindowHandle> firstWindow =
2342 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002343 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002344 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002345
2346 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002347 sp<FakeWindowHandle> secondWindow =
2348 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002349 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002350 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002351
2352 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002353 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002354
2355 PointF pointInFirst = {300, 200};
2356 PointF pointInSecond = {300, 600};
2357
2358 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002359 NotifyMotionArgs firstDownMotionArgs =
2360 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2361 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002362 mDispatcher->notifyMotion(&firstDownMotionArgs);
2363 // Only the first window should get the down event
2364 firstWindow->consumeMotionDown();
2365 secondWindow->assertNoEvents();
2366
2367 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002368 NotifyMotionArgs secondDownMotionArgs =
2369 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2370 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2371 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2372 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002373 mDispatcher->notifyMotion(&secondDownMotionArgs);
2374 // The first window gets a move and the second a down
2375 firstWindow->consumeMotionMove();
2376 secondWindow->consumeMotionDown();
2377
2378 // Transfer touch focus to the second window
2379 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2380 // The first window gets cancel and the new gets pointer down (it already saw down)
2381 firstWindow->consumeMotionCancel();
2382 secondWindow->consumeMotionPointerDown(1);
2383
2384 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002385 NotifyMotionArgs pointerUpMotionArgs =
2386 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2387 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2388 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2389 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002390 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2391 // The first window gets nothing and the second gets pointer up
2392 firstWindow->assertNoEvents();
2393 secondWindow->consumeMotionPointerUp(1);
2394
2395 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002396 NotifyMotionArgs upMotionArgs =
2397 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2398 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002399 mDispatcher->notifyMotion(&upMotionArgs);
2400 // The first window gets nothing and the second gets up
2401 firstWindow->assertNoEvents();
2402 secondWindow->consumeMotionUp();
2403}
2404
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002405// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2406// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2407// touch is not supported, so the touch should continue on those windows and the transferred-to
2408// window should get nothing.
2409TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2410 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2411
2412 // Create a non touch modal window that supports split touch
2413 sp<FakeWindowHandle> firstWindow =
2414 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2415 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002416 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002417
2418 // Create a non touch modal window that supports split touch
2419 sp<FakeWindowHandle> secondWindow =
2420 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2421 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002422 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002423
2424 // Add the windows to the dispatcher
2425 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2426
2427 PointF pointInFirst = {300, 200};
2428 PointF pointInSecond = {300, 600};
2429
2430 // Send down to the first window
2431 NotifyMotionArgs firstDownMotionArgs =
2432 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2433 ADISPLAY_ID_DEFAULT, {pointInFirst});
2434 mDispatcher->notifyMotion(&firstDownMotionArgs);
2435 // Only the first window should get the down event
2436 firstWindow->consumeMotionDown();
2437 secondWindow->assertNoEvents();
2438
2439 // Send down to the second window
2440 NotifyMotionArgs secondDownMotionArgs =
2441 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2442 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2443 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2444 {pointInFirst, pointInSecond});
2445 mDispatcher->notifyMotion(&secondDownMotionArgs);
2446 // The first window gets a move and the second a down
2447 firstWindow->consumeMotionMove();
2448 secondWindow->consumeMotionDown();
2449
2450 // Transfer touch focus to the second window
2451 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2452 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2453 ASSERT_FALSE(transferred);
2454 firstWindow->assertNoEvents();
2455 secondWindow->assertNoEvents();
2456
2457 // The rest of the dispatch should proceed as normal
2458 // Send pointer up to the second window
2459 NotifyMotionArgs pointerUpMotionArgs =
2460 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2461 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2462 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2463 {pointInFirst, pointInSecond});
2464 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2465 // The first window gets MOVE and the second gets pointer up
2466 firstWindow->consumeMotionMove();
2467 secondWindow->consumeMotionUp();
2468
2469 // Send up event to the first window
2470 NotifyMotionArgs upMotionArgs =
2471 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2472 ADISPLAY_ID_DEFAULT);
2473 mDispatcher->notifyMotion(&upMotionArgs);
2474 // The first window gets nothing and the second gets up
2475 firstWindow->consumeMotionUp();
2476 secondWindow->assertNoEvents();
2477}
2478
Arthur Hungabbb9d82021-09-01 14:52:30 +00002479// This case will create two windows and one mirrored window on the default display and mirror
2480// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2481// the windows info of second display before default display.
2482TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2483 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2484 sp<FakeWindowHandle> firstWindowInPrimary =
2485 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2486 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2487 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2488 sp<FakeWindowHandle> secondWindowInPrimary =
2489 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2490 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2491 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2492
2493 sp<FakeWindowHandle> mirrorWindowInPrimary =
2494 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2495 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2496 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2497
2498 sp<FakeWindowHandle> firstWindowInSecondary =
2499 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2500 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2501 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2502
2503 sp<FakeWindowHandle> secondWindowInSecondary =
2504 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2505 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2506 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2507
2508 // Update window info, let it find window handle of second display first.
2509 mDispatcher->setInputWindows(
2510 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2511 {ADISPLAY_ID_DEFAULT,
2512 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2513
2514 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2515 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2516 {50, 50}))
2517 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2518
2519 // Window should receive motion event.
2520 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2521
2522 // Transfer touch focus
2523 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2524 secondWindowInPrimary->getToken()));
2525 // The first window gets cancel.
2526 firstWindowInPrimary->consumeMotionCancel();
2527 secondWindowInPrimary->consumeMotionDown();
2528
2529 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2530 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2531 ADISPLAY_ID_DEFAULT, {150, 50}))
2532 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2533 firstWindowInPrimary->assertNoEvents();
2534 secondWindowInPrimary->consumeMotionMove();
2535
2536 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2537 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2538 {150, 50}))
2539 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2540 firstWindowInPrimary->assertNoEvents();
2541 secondWindowInPrimary->consumeMotionUp();
2542}
2543
2544// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2545// 'transferTouch' api.
2546TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2547 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2548 sp<FakeWindowHandle> firstWindowInPrimary =
2549 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2550 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2551 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2552 sp<FakeWindowHandle> secondWindowInPrimary =
2553 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2554 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2555 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2556
2557 sp<FakeWindowHandle> mirrorWindowInPrimary =
2558 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2559 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2560 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2561
2562 sp<FakeWindowHandle> firstWindowInSecondary =
2563 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2564 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2565 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2566
2567 sp<FakeWindowHandle> secondWindowInSecondary =
2568 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2569 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2570 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2571
2572 // Update window info, let it find window handle of second display first.
2573 mDispatcher->setInputWindows(
2574 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2575 {ADISPLAY_ID_DEFAULT,
2576 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2577
2578 // Touch on second display.
2579 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2580 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2581 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2582
2583 // Window should receive motion event.
2584 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2585
2586 // Transfer touch focus
2587 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2588
2589 // The first window gets cancel.
2590 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2591 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2592
2593 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2594 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2595 SECOND_DISPLAY_ID, {150, 50}))
2596 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2597 firstWindowInPrimary->assertNoEvents();
2598 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2599
2600 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2601 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2602 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2603 firstWindowInPrimary->assertNoEvents();
2604 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2605}
2606
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002607TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002608 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002609 sp<FakeWindowHandle> window =
2610 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2611
Vishnu Nair47074b82020-08-14 11:54:47 -07002612 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002613 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002614 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002615
2616 window->consumeFocusEvent(true);
2617
2618 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2619 mDispatcher->notifyKey(&keyArgs);
2620
2621 // Window should receive key down event.
2622 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2623}
2624
2625TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002626 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002627 sp<FakeWindowHandle> window =
2628 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2629
Arthur Hung72d8dc32020-03-28 00:48:39 +00002630 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002631
2632 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2633 mDispatcher->notifyKey(&keyArgs);
2634 mDispatcher->waitForIdle();
2635
2636 window->assertNoEvents();
2637}
2638
2639// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2640TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002641 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002642 sp<FakeWindowHandle> window =
2643 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2644
Arthur Hung72d8dc32020-03-28 00:48:39 +00002645 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002646
2647 // Send key
2648 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2649 mDispatcher->notifyKey(&keyArgs);
2650 // Send motion
2651 NotifyMotionArgs motionArgs =
2652 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2653 ADISPLAY_ID_DEFAULT);
2654 mDispatcher->notifyMotion(&motionArgs);
2655
2656 // Window should receive only the motion event
2657 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2658 window->assertNoEvents(); // Key event or focus event will not be received
2659}
2660
arthurhungea3f4fc2020-12-21 23:18:53 +08002661TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2662 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2663
2664 // Create first non touch modal window that supports split touch
2665 sp<FakeWindowHandle> firstWindow =
2666 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2667 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002668 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002669
2670 // Create second non touch modal window that supports split touch
2671 sp<FakeWindowHandle> secondWindow =
2672 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2673 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002674 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002675
2676 // Add the windows to the dispatcher
2677 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2678
2679 PointF pointInFirst = {300, 200};
2680 PointF pointInSecond = {300, 600};
2681
2682 // Send down to the first window
2683 NotifyMotionArgs firstDownMotionArgs =
2684 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2685 ADISPLAY_ID_DEFAULT, {pointInFirst});
2686 mDispatcher->notifyMotion(&firstDownMotionArgs);
2687 // Only the first window should get the down event
2688 firstWindow->consumeMotionDown();
2689 secondWindow->assertNoEvents();
2690
2691 // Send down to the second window
2692 NotifyMotionArgs secondDownMotionArgs =
2693 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2694 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2695 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2696 {pointInFirst, pointInSecond});
2697 mDispatcher->notifyMotion(&secondDownMotionArgs);
2698 // The first window gets a move and the second a down
2699 firstWindow->consumeMotionMove();
2700 secondWindow->consumeMotionDown();
2701
2702 // Send pointer cancel to the second window
2703 NotifyMotionArgs pointerUpMotionArgs =
2704 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2705 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2706 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2707 {pointInFirst, pointInSecond});
2708 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2709 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2710 // The first window gets move and the second gets cancel.
2711 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2712 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2713
2714 // Send up event.
2715 NotifyMotionArgs upMotionArgs =
2716 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2717 ADISPLAY_ID_DEFAULT);
2718 mDispatcher->notifyMotion(&upMotionArgs);
2719 // The first window gets up and the second gets nothing.
2720 firstWindow->consumeMotionUp();
2721 secondWindow->assertNoEvents();
2722}
2723
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002724TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2725 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2726
2727 sp<FakeWindowHandle> window =
2728 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2729 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2730 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2731 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2732 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2733
2734 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2735 window->assertNoEvents();
2736 mDispatcher->waitForIdle();
2737}
2738
chaviwd1c23182019-12-20 18:44:56 -08002739class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002740public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002741 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002742 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002743 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002744 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002745 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002746 }
2747
chaviwd1c23182019-12-20 18:44:56 -08002748 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2749
2750 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2751 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2752 expectedDisplayId, expectedFlags);
2753 }
2754
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002755 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2756
2757 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2758
chaviwd1c23182019-12-20 18:44:56 -08002759 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2760 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2761 expectedDisplayId, expectedFlags);
2762 }
2763
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002764 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2765 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2766 expectedDisplayId, expectedFlags);
2767 }
2768
chaviwd1c23182019-12-20 18:44:56 -08002769 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2770 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2771 expectedDisplayId, expectedFlags);
2772 }
2773
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002774 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2775 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2776 expectedDisplayId, expectedFlags);
2777 }
2778
Arthur Hungfbfa5722021-11-16 02:45:54 +00002779 void consumeMotionPointerDown(int32_t pointerIdx) {
2780 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2781 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2782 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2783 0 /*expectedFlags*/);
2784 }
2785
Evan Rosky84f07f02021-04-16 10:42:42 -07002786 MotionEvent* consumeMotion() {
2787 InputEvent* event = mInputReceiver->consume();
2788 if (!event) {
2789 ADD_FAILURE() << "No event was produced";
2790 return nullptr;
2791 }
2792 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2793 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2794 return nullptr;
2795 }
2796 return static_cast<MotionEvent*>(event);
2797 }
2798
chaviwd1c23182019-12-20 18:44:56 -08002799 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2800
2801private:
2802 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002803};
2804
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002805/**
2806 * Two entities that receive touch: A window, and a global monitor.
2807 * The touch goes to the window, and then the window disappears.
2808 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2809 * for the monitor, as well.
2810 * 1. foregroundWindow
2811 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2812 */
2813TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_GlobalMonitorTouchIsCanceled) {
2814 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2815 sp<FakeWindowHandle> window =
2816 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2817
2818 FakeMonitorReceiver monitor =
2819 FakeMonitorReceiver(mDispatcher, "GlobalMonitor", ADISPLAY_ID_DEFAULT,
2820 false /*isGestureMonitor*/);
2821
2822 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2823 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2824 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2825 {100, 200}))
2826 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2827
2828 // Both the foreground window and the global monitor should receive the touch down
2829 window->consumeMotionDown();
2830 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2831
2832 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2833 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2834 ADISPLAY_ID_DEFAULT, {110, 200}))
2835 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2836
2837 window->consumeMotionMove();
2838 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2839
2840 // Now the foreground window goes away
2841 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2842 window->consumeMotionCancel();
2843 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2844
2845 // If more events come in, there will be no more foreground window to send them to. This will
2846 // cause a cancel for the monitor, as well.
2847 ASSERT_EQ(InputEventInjectionResult::FAILED,
2848 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2849 ADISPLAY_ID_DEFAULT, {120, 200}))
2850 << "Injection should fail because the window was removed";
2851 window->assertNoEvents();
2852 // Global monitor now gets the cancel
2853 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2854}
2855
Michael Wright3a240c42019-12-10 20:53:41 +00002856// Tests for gesture monitors
2857TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002858 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002859 sp<FakeWindowHandle> window =
2860 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002861 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002862
chaviwd1c23182019-12-20 18:44:56 -08002863 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2864 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002865
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002866 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002867 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002868 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002869 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002870 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002871}
2872
2873TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002874 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002875 sp<FakeWindowHandle> window =
2876 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2877
2878 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002879 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002880
Arthur Hung72d8dc32020-03-28 00:48:39 +00002881 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002882 setFocusedWindow(window);
2883
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002884 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002885
chaviwd1c23182019-12-20 18:44:56 -08002886 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2887 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002888
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002889 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2890 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002891 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002892 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002893}
2894
2895TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002896 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002897 sp<FakeWindowHandle> window =
2898 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002899 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002900
chaviwd1c23182019-12-20 18:44:56 -08002901 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2902 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002903
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002904 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002905 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002906 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002907 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002908 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002909
2910 window->releaseChannel();
2911
chaviwd1c23182019-12-20 18:44:56 -08002912 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002913
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002914 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002915 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002916 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002917 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002918}
2919
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002920TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2921 FakeMonitorReceiver monitor =
2922 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2923 true /*isGestureMonitor*/);
2924
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002925 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002926 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2927 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2928 ASSERT_TRUE(consumeSeq);
2929
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002930 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002931 monitor.finishEvent(*consumeSeq);
2932 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002933 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002934}
2935
Evan Rosky84f07f02021-04-16 10:42:42 -07002936// Tests for gesture monitors
2937TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2938 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2939 sp<FakeWindowHandle> window =
2940 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2941 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2942 window->setWindowOffset(20, 40);
2943 window->setWindowTransform(0, 1, -1, 0);
2944
2945 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2946 true /*isGestureMonitor*/);
2947
2948 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2949 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2950 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2951 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2952 MotionEvent* event = monitor.consumeMotion();
2953 // Even though window has transform, gesture monitor must not.
2954 ASSERT_EQ(ui::Transform(), event->getTransform());
2955}
2956
Arthur Hungb3307ee2021-10-14 10:57:37 +00002957TEST_F(InputDispatcherTest, GestureMonitor_NoWindow) {
2958 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2959 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2960 true /*isGestureMonitor*/);
2961
2962 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2963 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2964 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2965 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2966}
2967
chaviw81e2bb92019-12-18 15:03:51 -08002968TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002969 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002970 sp<FakeWindowHandle> window =
2971 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2972
Arthur Hung72d8dc32020-03-28 00:48:39 +00002973 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002974
2975 NotifyMotionArgs motionArgs =
2976 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2977 ADISPLAY_ID_DEFAULT);
2978
2979 mDispatcher->notifyMotion(&motionArgs);
2980 // Window should receive motion down event.
2981 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2982
2983 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002984 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002985 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2986 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2987 motionArgs.pointerCoords[0].getX() - 10);
2988
2989 mDispatcher->notifyMotion(&motionArgs);
2990 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2991 0 /*expectedFlags*/);
2992}
2993
Arthur Hungfbfa5722021-11-16 02:45:54 +00002994TEST_F(InputDispatcherTest, GestureMonitor_SplitIfNoWindowTouched) {
2995 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2996 true /*isGestureMonitor*/);
2997
2998 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2999 // Create a non touch modal window that supports split touch
3000 sp<FakeWindowHandle> window =
3001 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3002 window->setFrame(Rect(0, 0, 100, 100));
3003 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
3004 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3005
3006 // First finger down, no window touched.
3007 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3008 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3009 {100, 200}))
3010 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3011 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3012 window->assertNoEvents();
3013
3014 // Second finger down on window, the window should receive touch down.
3015 const MotionEvent secondFingerDownEvent =
3016 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
3017 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
3018 AINPUT_SOURCE_TOUCHSCREEN)
3019 .displayId(ADISPLAY_ID_DEFAULT)
3020 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3021 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3022 .x(100)
3023 .y(200))
3024 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3025 .build();
3026 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3027 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
3028 InputEventInjectionSync::WAIT_FOR_RESULT))
3029 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3030
3031 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3032 monitor.consumeMotionPointerDown(1 /* pointerIndex */);
3033}
3034
3035TEST_F(InputDispatcherTest, GestureMonitor_NoSplitAfterPilfer) {
3036 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
3037 true /*isGestureMonitor*/);
3038
3039 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3040 // Create a non touch modal window that supports split touch
3041 sp<FakeWindowHandle> window =
3042 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3043 window->setFrame(Rect(0, 0, 100, 100));
3044 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
3045 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3046
3047 // First finger down, no window touched.
3048 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3049 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3050 {100, 200}))
3051 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3052 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3053 window->assertNoEvents();
3054
3055 // Gesture monitor pilfer the pointers.
3056 mDispatcher->pilferPointers(monitor.getToken());
3057
3058 // Second finger down on window, the window should not receive touch down.
3059 const MotionEvent secondFingerDownEvent =
3060 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
3061 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
3062 AINPUT_SOURCE_TOUCHSCREEN)
3063 .displayId(ADISPLAY_ID_DEFAULT)
3064 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3065 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3066 .x(100)
3067 .y(200))
3068 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3069 .build();
3070 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3071 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
3072 InputEventInjectionSync::WAIT_FOR_RESULT))
3073 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3074
3075 window->assertNoEvents();
3076 monitor.consumeMotionPointerDown(1 /* pointerIndex */);
3077}
3078
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003079/**
3080 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3081 * the device default right away. In the test scenario, we check both the default value,
3082 * and the action of enabling / disabling.
3083 */
3084TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003085 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003086 sp<FakeWindowHandle> window =
3087 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3088
3089 // Set focused application.
3090 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003091 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003092
3093 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003094 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003095 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003096 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3097
3098 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003099 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003100 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003101 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3102
3103 SCOPED_TRACE("Disable touch mode");
3104 mDispatcher->setInTouchMode(false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003105 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003106 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003107 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003108 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003109 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3110
3111 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003112 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003113 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003114 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3115
3116 SCOPED_TRACE("Enable touch mode again");
3117 mDispatcher->setInTouchMode(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003118 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003119 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003120 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003121 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003122 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3123
3124 window->assertNoEvents();
3125}
3126
Gang Wange9087892020-01-07 12:17:14 -05003127TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003128 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003129 sp<FakeWindowHandle> window =
3130 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3131
3132 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003133 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003134
Arthur Hung72d8dc32020-03-28 00:48:39 +00003135 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003136 setFocusedWindow(window);
3137
Gang Wange9087892020-01-07 12:17:14 -05003138 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3139
3140 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3141 mDispatcher->notifyKey(&keyArgs);
3142
3143 InputEvent* event = window->consume();
3144 ASSERT_NE(event, nullptr);
3145
3146 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3147 ASSERT_NE(verified, nullptr);
3148 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3149
3150 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3151 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3152 ASSERT_EQ(keyArgs.source, verified->source);
3153 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3154
3155 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3156
3157 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003158 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003159 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003160 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3161 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3162 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3163 ASSERT_EQ(0, verifiedKey.repeatCount);
3164}
3165
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003166TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003167 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003168 sp<FakeWindowHandle> window =
3169 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3170
3171 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3172
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003173 ui::Transform transform;
3174 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3175
3176 gui::DisplayInfo displayInfo;
3177 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3178 displayInfo.transform = transform;
3179
3180 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003181
3182 NotifyMotionArgs motionArgs =
3183 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3184 ADISPLAY_ID_DEFAULT);
3185 mDispatcher->notifyMotion(&motionArgs);
3186
3187 InputEvent* event = window->consume();
3188 ASSERT_NE(event, nullptr);
3189
3190 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3191 ASSERT_NE(verified, nullptr);
3192 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3193
3194 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3195 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3196 EXPECT_EQ(motionArgs.source, verified->source);
3197 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3198
3199 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3200
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003201 const vec2 rawXY =
3202 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3203 motionArgs.pointerCoords[0].getXYValue());
3204 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3205 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003206 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003207 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003208 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003209 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3210 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3211}
3212
chaviw09c8d2d2020-08-24 15:48:26 -07003213/**
3214 * Ensure that separate calls to sign the same data are generating the same key.
3215 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3216 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3217 * tests.
3218 */
3219TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3220 KeyEvent event = getTestKeyEvent();
3221 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3222
3223 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3224 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3225 ASSERT_EQ(hmac1, hmac2);
3226}
3227
3228/**
3229 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3230 */
3231TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3232 KeyEvent event = getTestKeyEvent();
3233 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3234 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3235
3236 verifiedEvent.deviceId += 1;
3237 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3238
3239 verifiedEvent.source += 1;
3240 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3241
3242 verifiedEvent.eventTimeNanos += 1;
3243 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3244
3245 verifiedEvent.displayId += 1;
3246 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3247
3248 verifiedEvent.action += 1;
3249 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3250
3251 verifiedEvent.downTimeNanos += 1;
3252 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3253
3254 verifiedEvent.flags += 1;
3255 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3256
3257 verifiedEvent.keyCode += 1;
3258 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3259
3260 verifiedEvent.scanCode += 1;
3261 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3262
3263 verifiedEvent.metaState += 1;
3264 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3265
3266 verifiedEvent.repeatCount += 1;
3267 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3268}
3269
Vishnu Nair958da932020-08-21 17:12:37 -07003270TEST_F(InputDispatcherTest, SetFocusedWindow) {
3271 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3272 sp<FakeWindowHandle> windowTop =
3273 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3274 sp<FakeWindowHandle> windowSecond =
3275 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3276 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3277
3278 // Top window is also focusable but is not granted focus.
3279 windowTop->setFocusable(true);
3280 windowSecond->setFocusable(true);
3281 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3282 setFocusedWindow(windowSecond);
3283
3284 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003285 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3286 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003287
3288 // Focused window should receive event.
3289 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3290 windowTop->assertNoEvents();
3291}
3292
3293TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3294 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3295 sp<FakeWindowHandle> window =
3296 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3297 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3298
3299 window->setFocusable(true);
3300 // Release channel for window is no longer valid.
3301 window->releaseChannel();
3302 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3303 setFocusedWindow(window);
3304
3305 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003306 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3307 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003308
3309 // window channel is invalid, so it should not receive any input event.
3310 window->assertNoEvents();
3311}
3312
3313TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3314 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3315 sp<FakeWindowHandle> window =
3316 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3317 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3318
3319 // Window is not focusable.
3320 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3321 setFocusedWindow(window);
3322
3323 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003324 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3325 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003326
3327 // window is invalid, so it should not receive any input event.
3328 window->assertNoEvents();
3329}
3330
3331TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3332 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3333 sp<FakeWindowHandle> windowTop =
3334 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3335 sp<FakeWindowHandle> windowSecond =
3336 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3337 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3338
3339 windowTop->setFocusable(true);
3340 windowSecond->setFocusable(true);
3341 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3342 setFocusedWindow(windowTop);
3343 windowTop->consumeFocusEvent(true);
3344
3345 setFocusedWindow(windowSecond, windowTop);
3346 windowSecond->consumeFocusEvent(true);
3347 windowTop->consumeFocusEvent(false);
3348
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003349 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3350 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003351
3352 // Focused window should receive event.
3353 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3354}
3355
3356TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3357 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3358 sp<FakeWindowHandle> windowTop =
3359 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3360 sp<FakeWindowHandle> windowSecond =
3361 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3362 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3363
3364 windowTop->setFocusable(true);
3365 windowSecond->setFocusable(true);
3366 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3367 setFocusedWindow(windowSecond, windowTop);
3368
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003369 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3370 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003371
3372 // Event should be dropped.
3373 windowTop->assertNoEvents();
3374 windowSecond->assertNoEvents();
3375}
3376
3377TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3378 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3379 sp<FakeWindowHandle> window =
3380 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3381 sp<FakeWindowHandle> previousFocusedWindow =
3382 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3383 ADISPLAY_ID_DEFAULT);
3384 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3385
3386 window->setFocusable(true);
3387 previousFocusedWindow->setFocusable(true);
3388 window->setVisible(false);
3389 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3390 setFocusedWindow(previousFocusedWindow);
3391 previousFocusedWindow->consumeFocusEvent(true);
3392
3393 // Requesting focus on invisible window takes focus from currently focused window.
3394 setFocusedWindow(window);
3395 previousFocusedWindow->consumeFocusEvent(false);
3396
3397 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003398 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003399 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003400 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003401
3402 // Window does not get focus event or key down.
3403 window->assertNoEvents();
3404
3405 // Window becomes visible.
3406 window->setVisible(true);
3407 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3408
3409 // Window receives focus event.
3410 window->consumeFocusEvent(true);
3411 // Focused window receives key down.
3412 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3413}
3414
Vishnu Nair599f1412021-06-21 10:39:58 -07003415TEST_F(InputDispatcherTest, DisplayRemoved) {
3416 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3417 sp<FakeWindowHandle> window =
3418 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3419 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3420
3421 // window is granted focus.
3422 window->setFocusable(true);
3423 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3424 setFocusedWindow(window);
3425 window->consumeFocusEvent(true);
3426
3427 // When a display is removed window loses focus.
3428 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3429 window->consumeFocusEvent(false);
3430}
3431
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003432/**
3433 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3434 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3435 * of the 'slipperyEnterWindow'.
3436 *
3437 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3438 * a way so that the touched location is no longer covered by the top window.
3439 *
3440 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3441 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3442 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3443 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3444 * with ACTION_DOWN).
3445 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3446 * window moved itself away from the touched location and had Flag::SLIPPERY.
3447 *
3448 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3449 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3450 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3451 *
3452 * In this test, we ensure that the event received by the bottom window has
3453 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3454 */
3455TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3456 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3457 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3458
3459 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3460 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3461
3462 sp<FakeWindowHandle> slipperyExitWindow =
3463 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003464 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003465 // Make sure this one overlaps the bottom window
3466 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3467 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3468 // one. Windows with the same owner are not considered to be occluding each other.
3469 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3470
3471 sp<FakeWindowHandle> slipperyEnterWindow =
3472 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3473 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3474
3475 mDispatcher->setInputWindows(
3476 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3477
3478 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3479 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3480 ADISPLAY_ID_DEFAULT, {{50, 50}});
3481 mDispatcher->notifyMotion(&args);
3482 slipperyExitWindow->consumeMotionDown();
3483 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3484 mDispatcher->setInputWindows(
3485 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3486
3487 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3488 ADISPLAY_ID_DEFAULT, {{51, 51}});
3489 mDispatcher->notifyMotion(&args);
3490
3491 slipperyExitWindow->consumeMotionCancel();
3492
3493 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3494 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3495}
3496
Garfield Tan1c7bc862020-01-28 13:24:04 -08003497class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3498protected:
3499 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3500 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3501
Chris Yea209fde2020-07-22 13:54:51 -07003502 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003503 sp<FakeWindowHandle> mWindow;
3504
3505 virtual void SetUp() override {
3506 mFakePolicy = new FakeInputDispatcherPolicy();
3507 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003508 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003509 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3510 ASSERT_EQ(OK, mDispatcher->start());
3511
3512 setUpWindow();
3513 }
3514
3515 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003516 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003517 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3518
Vishnu Nair47074b82020-08-14 11:54:47 -07003519 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003520 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003521 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003522 mWindow->consumeFocusEvent(true);
3523 }
3524
Chris Ye2ad95392020-09-01 13:44:44 -07003525 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003526 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003527 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003528 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3529 mDispatcher->notifyKey(&keyArgs);
3530
3531 // Window should receive key down event.
3532 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3533 }
3534
3535 void expectKeyRepeatOnce(int32_t repeatCount) {
3536 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3537 InputEvent* repeatEvent = mWindow->consume();
3538 ASSERT_NE(nullptr, repeatEvent);
3539
3540 uint32_t eventType = repeatEvent->getType();
3541 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3542
3543 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3544 uint32_t eventAction = repeatKeyEvent->getAction();
3545 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3546 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3547 }
3548
Chris Ye2ad95392020-09-01 13:44:44 -07003549 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003550 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003551 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003552 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3553 mDispatcher->notifyKey(&keyArgs);
3554
3555 // Window should receive key down event.
3556 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3557 0 /*expectedFlags*/);
3558 }
3559};
3560
3561TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003562 sendAndConsumeKeyDown(1 /* deviceId */);
3563 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3564 expectKeyRepeatOnce(repeatCount);
3565 }
3566}
3567
3568TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3569 sendAndConsumeKeyDown(1 /* deviceId */);
3570 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3571 expectKeyRepeatOnce(repeatCount);
3572 }
3573 sendAndConsumeKeyDown(2 /* deviceId */);
3574 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003575 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3576 expectKeyRepeatOnce(repeatCount);
3577 }
3578}
3579
3580TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003581 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003582 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003583 sendAndConsumeKeyUp(1 /* deviceId */);
3584 mWindow->assertNoEvents();
3585}
3586
3587TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3588 sendAndConsumeKeyDown(1 /* deviceId */);
3589 expectKeyRepeatOnce(1 /*repeatCount*/);
3590 sendAndConsumeKeyDown(2 /* deviceId */);
3591 expectKeyRepeatOnce(1 /*repeatCount*/);
3592 // Stale key up from device 1.
3593 sendAndConsumeKeyUp(1 /* deviceId */);
3594 // Device 2 is still down, keep repeating
3595 expectKeyRepeatOnce(2 /*repeatCount*/);
3596 expectKeyRepeatOnce(3 /*repeatCount*/);
3597 // Device 2 key up
3598 sendAndConsumeKeyUp(2 /* deviceId */);
3599 mWindow->assertNoEvents();
3600}
3601
3602TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3603 sendAndConsumeKeyDown(1 /* deviceId */);
3604 expectKeyRepeatOnce(1 /*repeatCount*/);
3605 sendAndConsumeKeyDown(2 /* deviceId */);
3606 expectKeyRepeatOnce(1 /*repeatCount*/);
3607 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3608 sendAndConsumeKeyUp(2 /* deviceId */);
3609 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003610 mWindow->assertNoEvents();
3611}
3612
liushenxiang42232912021-05-21 20:24:09 +08003613TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3614 sendAndConsumeKeyDown(DEVICE_ID);
3615 expectKeyRepeatOnce(1 /*repeatCount*/);
3616 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3617 mDispatcher->notifyDeviceReset(&args);
3618 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3619 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3620 mWindow->assertNoEvents();
3621}
3622
Garfield Tan1c7bc862020-01-28 13:24:04 -08003623TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003624 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003625 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3626 InputEvent* repeatEvent = mWindow->consume();
3627 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3628 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3629 IdGenerator::getSource(repeatEvent->getId()));
3630 }
3631}
3632
3633TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003634 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003635
3636 std::unordered_set<int32_t> idSet;
3637 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3638 InputEvent* repeatEvent = mWindow->consume();
3639 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3640 int32_t id = repeatEvent->getId();
3641 EXPECT_EQ(idSet.end(), idSet.find(id));
3642 idSet.insert(id);
3643 }
3644}
3645
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003646/* Test InputDispatcher for MultiDisplay */
3647class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3648public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003649 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003650 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003651
Chris Yea209fde2020-07-22 13:54:51 -07003652 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003653 windowInPrimary =
3654 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003655
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003656 // Set focus window for primary display, but focused display would be second one.
3657 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003658 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003659 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003660 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003661 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003662
Chris Yea209fde2020-07-22 13:54:51 -07003663 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003664 windowInSecondary =
3665 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003666 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003667 // Set focus display to second one.
3668 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3669 // Set focus window for second display.
3670 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003671 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003672 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003673 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003674 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003675 }
3676
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003677 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003678 InputDispatcherTest::TearDown();
3679
Chris Yea209fde2020-07-22 13:54:51 -07003680 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003681 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003682 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003683 windowInSecondary.clear();
3684 }
3685
3686protected:
Chris Yea209fde2020-07-22 13:54:51 -07003687 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003688 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003689 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003690 sp<FakeWindowHandle> windowInSecondary;
3691};
3692
3693TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3694 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003695 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3696 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3697 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003698 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003699 windowInSecondary->assertNoEvents();
3700
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003701 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003702 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3703 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3704 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003705 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003706 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003707}
3708
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003709TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003710 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003711 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3712 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003713 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003714 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003715 windowInSecondary->assertNoEvents();
3716
3717 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003718 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003719 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003720 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003721 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003722
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003723 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003724 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003725
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003726 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003727 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3728 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003729
3730 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003731 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003732 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003733 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003734 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003735 windowInSecondary->assertNoEvents();
3736}
3737
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003738// Test per-display input monitors for motion event.
3739TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003740 FakeMonitorReceiver monitorInPrimary =
3741 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3742 FakeMonitorReceiver monitorInSecondary =
3743 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003744
3745 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003746 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3747 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3748 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003749 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003750 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003751 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003752 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003753
3754 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003755 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3756 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3757 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003758 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003759 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003760 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003761 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003762
3763 // Test inject a non-pointer motion event.
3764 // If specific a display, it will dispatch to the focused window of particular display,
3765 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003766 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3767 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3768 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003769 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003770 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003771 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003772 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003773}
3774
3775// Test per-display input monitors for key event.
3776TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003777 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003778 FakeMonitorReceiver monitorInPrimary =
3779 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3780 FakeMonitorReceiver monitorInSecondary =
3781 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003782
3783 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003784 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3785 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003786 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003787 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003788 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003789 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003790}
3791
Vishnu Nair958da932020-08-21 17:12:37 -07003792TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3793 sp<FakeWindowHandle> secondWindowInPrimary =
3794 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3795 secondWindowInPrimary->setFocusable(true);
3796 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3797 setFocusedWindow(secondWindowInPrimary);
3798 windowInPrimary->consumeFocusEvent(false);
3799 secondWindowInPrimary->consumeFocusEvent(true);
3800
3801 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003802 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3803 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003804 windowInPrimary->assertNoEvents();
3805 windowInSecondary->assertNoEvents();
3806 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3807}
3808
Arthur Hungdfd528e2021-12-08 13:23:04 +00003809TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3810 FakeMonitorReceiver monitorInPrimary =
3811 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3812 FakeMonitorReceiver monitorInSecondary =
3813 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3814
3815 // Test touch down on primary display.
3816 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3817 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3818 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3819 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3820 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3821
3822 // Test touch down on second display.
3823 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3824 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3825 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3826 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3827 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3828
3829 // Trigger cancel touch.
3830 mDispatcher->cancelCurrentTouch();
3831 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3832 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3833 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3834 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3835
3836 // Test inject a move motion event, no window/monitor should receive the event.
3837 ASSERT_EQ(InputEventInjectionResult::FAILED,
3838 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3839 ADISPLAY_ID_DEFAULT, {110, 200}))
3840 << "Inject motion event should return InputEventInjectionResult::FAILED";
3841 windowInPrimary->assertNoEvents();
3842 monitorInPrimary.assertNoEvents();
3843
3844 ASSERT_EQ(InputEventInjectionResult::FAILED,
3845 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3846 SECOND_DISPLAY_ID, {110, 200}))
3847 << "Inject motion event should return InputEventInjectionResult::FAILED";
3848 windowInSecondary->assertNoEvents();
3849 monitorInSecondary.assertNoEvents();
3850}
3851
Jackal Guof9696682018-10-05 12:23:23 +08003852class InputFilterTest : public InputDispatcherTest {
3853protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003854 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3855 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003856 NotifyMotionArgs motionArgs;
3857
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003858 motionArgs =
3859 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003860 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003861 motionArgs =
3862 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003863 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003864 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003865 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003866 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3867 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003868 } else {
3869 mFakePolicy->assertFilterInputEventWasNotCalled();
3870 }
3871 }
3872
3873 void testNotifyKey(bool expectToBeFiltered) {
3874 NotifyKeyArgs keyArgs;
3875
3876 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3877 mDispatcher->notifyKey(&keyArgs);
3878 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3879 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003880 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003881
3882 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003883 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003884 } else {
3885 mFakePolicy->assertFilterInputEventWasNotCalled();
3886 }
3887 }
3888};
3889
3890// Test InputFilter for MotionEvent
3891TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3892 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3893 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3894 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3895
3896 // Enable InputFilter
3897 mDispatcher->setInputFilterEnabled(true);
3898 // Test touch on both primary and second display, and check if both events are filtered.
3899 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3900 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3901
3902 // Disable InputFilter
3903 mDispatcher->setInputFilterEnabled(false);
3904 // Test touch on both primary and second display, and check if both events aren't filtered.
3905 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3906 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3907}
3908
3909// Test InputFilter for KeyEvent
3910TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3911 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3912 testNotifyKey(/*expectToBeFiltered*/ false);
3913
3914 // Enable InputFilter
3915 mDispatcher->setInputFilterEnabled(true);
3916 // Send a key event, and check if it is filtered.
3917 testNotifyKey(/*expectToBeFiltered*/ true);
3918
3919 // Disable InputFilter
3920 mDispatcher->setInputFilterEnabled(false);
3921 // Send a key event, and check if it isn't filtered.
3922 testNotifyKey(/*expectToBeFiltered*/ false);
3923}
3924
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003925// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3926// logical display coordinate space.
3927TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3928 ui::Transform firstDisplayTransform;
3929 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3930 ui::Transform secondDisplayTransform;
3931 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3932
3933 std::vector<gui::DisplayInfo> displayInfos(2);
3934 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3935 displayInfos[0].transform = firstDisplayTransform;
3936 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3937 displayInfos[1].transform = secondDisplayTransform;
3938
3939 mDispatcher->onWindowInfosChanged({}, displayInfos);
3940
3941 // Enable InputFilter
3942 mDispatcher->setInputFilterEnabled(true);
3943
3944 // Ensure the correct transforms are used for the displays.
3945 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3946 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3947}
3948
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003949class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3950protected:
3951 virtual void SetUp() override {
3952 InputDispatcherTest::SetUp();
3953
3954 /**
3955 * We don't need to enable input filter to test the injected event policy, but we enabled it
3956 * here to make the tests more realistic, since this policy only matters when inputfilter is
3957 * on.
3958 */
3959 mDispatcher->setInputFilterEnabled(true);
3960
3961 std::shared_ptr<InputApplicationHandle> application =
3962 std::make_shared<FakeApplicationHandle>();
3963 mWindow =
3964 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3965
3966 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3967 mWindow->setFocusable(true);
3968 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3969 setFocusedWindow(mWindow);
3970 mWindow->consumeFocusEvent(true);
3971 }
3972
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003973 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3974 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003975 KeyEvent event;
3976
3977 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3978 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3979 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3980 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3981 const int32_t additionalPolicyFlags =
3982 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3983 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3984 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3985 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3986 policyFlags | additionalPolicyFlags));
3987
3988 InputEvent* received = mWindow->consume();
3989 ASSERT_NE(nullptr, received);
3990 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003991 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3992 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3993 ASSERT_EQ(flags, keyEvent.getFlags());
3994 }
3995
3996 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3997 int32_t flags) {
3998 MotionEvent event;
3999 PointerProperties pointerProperties[1];
4000 PointerCoords pointerCoords[1];
4001 pointerProperties[0].clear();
4002 pointerProperties[0].id = 0;
4003 pointerCoords[0].clear();
4004 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4005 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4006
4007 ui::Transform identityTransform;
4008 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4009 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4010 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4011 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4012 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004013 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004014 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004015 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4016
4017 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4018 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4019 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
4020 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4021 policyFlags | additionalPolicyFlags));
4022
4023 InputEvent* received = mWindow->consume();
4024 ASSERT_NE(nullptr, received);
4025 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4026 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4027 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4028 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004029 }
4030
4031private:
4032 sp<FakeWindowHandle> mWindow;
4033};
4034
4035TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004036 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4037 // filter. Without it, the event will no different from a regularly injected event, and the
4038 // injected device id will be overwritten.
4039 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4040 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004041}
4042
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004043TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004044 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004045 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4046 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4047}
4048
4049TEST_F(InputFilterInjectionPolicyTest,
4050 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4051 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4052 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4053 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004054}
4055
4056TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4057 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004058 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004059}
4060
chaviwfd6d3512019-03-25 13:23:49 -07004061class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004062 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004063 InputDispatcherTest::SetUp();
4064
Chris Yea209fde2020-07-22 13:54:51 -07004065 std::shared_ptr<FakeApplicationHandle> application =
4066 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004067 mUnfocusedWindow =
4068 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004069 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4070 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4071 // window.
chaviw3277faf2021-05-19 16:45:23 -05004072 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07004073
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004074 mFocusedWindow =
4075 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4076 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004077 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07004078
4079 // Set focused application.
4080 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004081 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004082
4083 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004084 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004085 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004086 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004087 }
4088
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004089 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004090 InputDispatcherTest::TearDown();
4091
4092 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004093 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004094 }
4095
4096protected:
4097 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004098 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004099 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004100};
4101
4102// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4103// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4104// the onPointerDownOutsideFocus callback.
4105TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004106 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004107 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4108 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004109 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004110 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004111
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004112 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004113 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4114}
4115
4116// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4117// DOWN on the window that doesn't have focus. Ensure no window received the
4118// onPointerDownOutsideFocus callback.
4119TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004120 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004121 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004122 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004123 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004124
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004125 ASSERT_TRUE(mDispatcher->waitForIdle());
4126 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004127}
4128
4129// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4130// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4131TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004132 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4133 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004134 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004135 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004136
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004137 ASSERT_TRUE(mDispatcher->waitForIdle());
4138 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004139}
4140
4141// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4142// DOWN on the window that already has focus. Ensure no window received the
4143// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004144TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004145 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004146 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004147 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004148 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004149 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004150
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004151 ASSERT_TRUE(mDispatcher->waitForIdle());
4152 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004153}
4154
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004155// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4156// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4157TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4158 const MotionEvent event =
4159 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4160 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4161 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4162 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4163 .build();
4164 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4165 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4166 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4167
4168 ASSERT_TRUE(mDispatcher->waitForIdle());
4169 mFakePolicy->assertOnPointerDownWasNotCalled();
4170 // Ensure that the unfocused window did not receive any FOCUS events.
4171 mUnfocusedWindow->assertNoEvents();
4172}
4173
chaviwaf87b3e2019-10-01 16:59:28 -07004174// These tests ensures we can send touch events to a single client when there are multiple input
4175// windows that point to the same client token.
4176class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4177 virtual void SetUp() override {
4178 InputDispatcherTest::SetUp();
4179
Chris Yea209fde2020-07-22 13:54:51 -07004180 std::shared_ptr<FakeApplicationHandle> application =
4181 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004182 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4183 ADISPLAY_ID_DEFAULT);
4184 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
4185 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05004186 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004187 mWindow1->setFrame(Rect(0, 0, 100, 100));
4188
4189 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4190 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05004191 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004192 mWindow2->setFrame(Rect(100, 100, 200, 200));
4193
Arthur Hung72d8dc32020-03-28 00:48:39 +00004194 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004195 }
4196
4197protected:
4198 sp<FakeWindowHandle> mWindow1;
4199 sp<FakeWindowHandle> mWindow2;
4200
4201 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004202 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004203 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4204 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004205 }
4206
4207 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4208 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004209 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004210 InputEvent* event = window->consume();
4211
4212 ASSERT_NE(nullptr, event) << name.c_str()
4213 << ": consumer should have returned non-NULL event.";
4214
4215 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4216 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4217 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4218
4219 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004220 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004221
4222 for (size_t i = 0; i < points.size(); i++) {
4223 float expectedX = points[i].x;
4224 float expectedY = points[i].y;
4225
4226 EXPECT_EQ(expectedX, motionEvent.getX(i))
4227 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4228 << ", got " << motionEvent.getX(i);
4229 EXPECT_EQ(expectedY, motionEvent.getY(i))
4230 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4231 << ", got " << motionEvent.getY(i);
4232 }
4233 }
chaviw9eaa22c2020-07-01 16:21:27 -07004234
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004235 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004236 std::vector<PointF> expectedPoints) {
4237 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4238 ADISPLAY_ID_DEFAULT, touchedPoints);
4239 mDispatcher->notifyMotion(&motionArgs);
4240
4241 // Always consume from window1 since it's the window that has the InputReceiver
4242 consumeMotionEvent(mWindow1, action, expectedPoints);
4243 }
chaviwaf87b3e2019-10-01 16:59:28 -07004244};
4245
4246TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4247 // Touch Window 1
4248 PointF touchedPoint = {10, 10};
4249 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004250 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004251
4252 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004253 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004254
4255 // Touch Window 2
4256 touchedPoint = {150, 150};
4257 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004258 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004259}
4260
chaviw9eaa22c2020-07-01 16:21:27 -07004261TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4262 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004263 mWindow2->setWindowScale(0.5f, 0.5f);
4264
4265 // Touch Window 1
4266 PointF touchedPoint = {10, 10};
4267 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004268 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004269 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004270 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004271
4272 // Touch Window 2
4273 touchedPoint = {150, 150};
4274 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004275 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4276 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004277
chaviw9eaa22c2020-07-01 16:21:27 -07004278 // Update the transform so rotation is set
4279 mWindow2->setWindowTransform(0, -1, 1, 0);
4280 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4281 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004282}
4283
chaviw9eaa22c2020-07-01 16:21:27 -07004284TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004285 mWindow2->setWindowScale(0.5f, 0.5f);
4286
4287 // Touch Window 1
4288 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4289 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004290 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004291
4292 // Touch Window 2
4293 int32_t actionPointerDown =
4294 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004295 touchedPoints.push_back(PointF{150, 150});
4296 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4297 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004298
chaviw9eaa22c2020-07-01 16:21:27 -07004299 // Release Window 2
4300 int32_t actionPointerUp =
4301 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4302 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4303 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004304
chaviw9eaa22c2020-07-01 16:21:27 -07004305 // Update the transform so rotation is set for Window 2
4306 mWindow2->setWindowTransform(0, -1, 1, 0);
4307 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4308 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004309}
4310
chaviw9eaa22c2020-07-01 16:21:27 -07004311TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004312 mWindow2->setWindowScale(0.5f, 0.5f);
4313
4314 // Touch Window 1
4315 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4316 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004317 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004318
4319 // Touch Window 2
4320 int32_t actionPointerDown =
4321 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004322 touchedPoints.push_back(PointF{150, 150});
4323 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004324
chaviw9eaa22c2020-07-01 16:21:27 -07004325 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004326
4327 // Move both windows
4328 touchedPoints = {{20, 20}, {175, 175}};
4329 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4330 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4331
chaviw9eaa22c2020-07-01 16:21:27 -07004332 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004333
chaviw9eaa22c2020-07-01 16:21:27 -07004334 // Release Window 2
4335 int32_t actionPointerUp =
4336 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4337 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4338 expectedPoints.pop_back();
4339
4340 // Touch Window 2
4341 mWindow2->setWindowTransform(0, -1, 1, 0);
4342 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4343 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4344
4345 // Move both windows
4346 touchedPoints = {{20, 20}, {175, 175}};
4347 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4348 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4349
4350 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004351}
4352
4353TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4354 mWindow1->setWindowScale(0.5f, 0.5f);
4355
4356 // Touch Window 1
4357 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4358 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004359 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004360
4361 // Touch Window 2
4362 int32_t actionPointerDown =
4363 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004364 touchedPoints.push_back(PointF{150, 150});
4365 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004366
chaviw9eaa22c2020-07-01 16:21:27 -07004367 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004368
4369 // Move both windows
4370 touchedPoints = {{20, 20}, {175, 175}};
4371 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4372 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4373
chaviw9eaa22c2020-07-01 16:21:27 -07004374 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004375}
4376
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004377class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4378 virtual void SetUp() override {
4379 InputDispatcherTest::SetUp();
4380
Chris Yea209fde2020-07-22 13:54:51 -07004381 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004382 mApplication->setDispatchingTimeout(20ms);
4383 mWindow =
4384 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4385 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004386 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004387 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004388 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4389 // window.
chaviw3277faf2021-05-19 16:45:23 -05004390 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004391
4392 // Set focused application.
4393 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4394
4395 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004396 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004397 mWindow->consumeFocusEvent(true);
4398 }
4399
4400 virtual void TearDown() override {
4401 InputDispatcherTest::TearDown();
4402 mWindow.clear();
4403 }
4404
4405protected:
Chris Yea209fde2020-07-22 13:54:51 -07004406 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004407 sp<FakeWindowHandle> mWindow;
4408 static constexpr PointF WINDOW_LOCATION = {20, 20};
4409
4410 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004411 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004412 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4413 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004414 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004415 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4416 WINDOW_LOCATION));
4417 }
4418};
4419
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004420// Send a tap and respond, which should not cause an ANR.
4421TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4422 tapOnWindow();
4423 mWindow->consumeMotionDown();
4424 mWindow->consumeMotionUp();
4425 ASSERT_TRUE(mDispatcher->waitForIdle());
4426 mFakePolicy->assertNotifyAnrWasNotCalled();
4427}
4428
4429// Send a regular key and respond, which should not cause an ANR.
4430TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004431 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004432 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4433 ASSERT_TRUE(mDispatcher->waitForIdle());
4434 mFakePolicy->assertNotifyAnrWasNotCalled();
4435}
4436
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004437TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4438 mWindow->setFocusable(false);
4439 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4440 mWindow->consumeFocusEvent(false);
4441
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004442 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004443 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004444 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4445 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004446 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004447 // Key will not go to window because we have no focused window.
4448 // The 'no focused window' ANR timer should start instead.
4449
4450 // Now, the focused application goes away.
4451 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4452 // The key should get dropped and there should be no ANR.
4453
4454 ASSERT_TRUE(mDispatcher->waitForIdle());
4455 mFakePolicy->assertNotifyAnrWasNotCalled();
4456}
4457
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004458// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004459// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4460// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004461TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004462 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004463 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4464 WINDOW_LOCATION));
4465
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004466 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4467 ASSERT_TRUE(sequenceNum);
4468 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004469 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004470
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004471 mWindow->finishEvent(*sequenceNum);
4472 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4473 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004474 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004475 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004476}
4477
4478// Send a key to the app and have the app not respond right away.
4479TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4480 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004481 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004482 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4483 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004484 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004485 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004486 ASSERT_TRUE(mDispatcher->waitForIdle());
4487}
4488
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004489// We have a focused application, but no focused window
4490TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004491 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004492 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4493 mWindow->consumeFocusEvent(false);
4494
4495 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004496 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004497 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4498 WINDOW_LOCATION));
4499 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4500 mDispatcher->waitForIdle();
4501 mFakePolicy->assertNotifyAnrWasNotCalled();
4502
4503 // Once a focused event arrives, we get an ANR for this application
4504 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4505 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004506 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004507 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004508 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004509 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004510 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004511 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004512 ASSERT_TRUE(mDispatcher->waitForIdle());
4513}
4514
4515// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004516// Make sure that we don't notify policy twice about the same ANR.
4517TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004518 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004519 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4520 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004521
4522 // Once a focused event arrives, we get an ANR for this application
4523 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4524 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004525 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004526 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004527 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004528 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004529 const std::chrono::duration appTimeout =
4530 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004531 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004532
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004533 std::this_thread::sleep_for(appTimeout);
4534 // ANR should not be raised again. It is up to policy to do that if it desires.
4535 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004536
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004537 // If we now get a focused window, the ANR should stop, but the policy handles that via
4538 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004539 ASSERT_TRUE(mDispatcher->waitForIdle());
4540}
4541
4542// We have a focused application, but no focused window
4543TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004544 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004545 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4546 mWindow->consumeFocusEvent(false);
4547
4548 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004549 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004550 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004551 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4552 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004553
4554 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004555 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004556
4557 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004558 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004559 ASSERT_TRUE(mDispatcher->waitForIdle());
4560 mWindow->assertNoEvents();
4561}
4562
4563/**
4564 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4565 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4566 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4567 * the ANR mechanism should still work.
4568 *
4569 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4570 * DOWN event, while not responding on the second one.
4571 */
4572TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4573 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4574 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4575 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4576 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4577 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004578 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004579
4580 // Now send ACTION_UP, with identical timestamp
4581 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4582 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4583 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4584 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004585 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004586
4587 // We have now sent down and up. Let's consume first event and then ANR on the second.
4588 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4589 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004590 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004591}
4592
4593// If an app is not responding to a key event, gesture monitors should continue to receive
4594// new motion events
4595TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
4596 FakeMonitorReceiver monitor =
4597 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4598 true /*isGestureMonitor*/);
4599
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004600 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4601 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004602 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004603 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004604
4605 // Stuck on the ACTION_UP
4606 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004607 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004608
4609 // New tap will go to the gesture monitor, but not to the window
4610 tapOnWindow();
4611 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4612 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4613
4614 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4615 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004616 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004617 mWindow->assertNoEvents();
4618 monitor.assertNoEvents();
4619}
4620
4621// If an app is not responding to a motion event, gesture monitors should continue to receive
4622// new motion events
4623TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
4624 FakeMonitorReceiver monitor =
4625 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4626 true /*isGestureMonitor*/);
4627
4628 tapOnWindow();
4629 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4630 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4631
4632 mWindow->consumeMotionDown();
4633 // Stuck on the ACTION_UP
4634 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004635 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004636
4637 // New tap will go to the gesture monitor, but not to the window
4638 tapOnWindow();
4639 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4640 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4641
4642 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4643 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004644 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004645 mWindow->assertNoEvents();
4646 monitor.assertNoEvents();
4647}
4648
4649// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4650// process events, you don't get an anr. When the window later becomes unresponsive again, you
4651// get an ANR again.
4652// 1. tap -> block on ACTION_UP -> receive ANR
4653// 2. consume all pending events (= queue becomes healthy again)
4654// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4655TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4656 tapOnWindow();
4657
4658 mWindow->consumeMotionDown();
4659 // Block on ACTION_UP
4660 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004661 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004662 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4663 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004664 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004665 mWindow->assertNoEvents();
4666
4667 tapOnWindow();
4668 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004669 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004670 mWindow->consumeMotionUp();
4671
4672 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004673 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004674 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004675 mWindow->assertNoEvents();
4676}
4677
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004678// If a connection remains unresponsive for a while, make sure policy is only notified once about
4679// it.
4680TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004681 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004682 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4683 WINDOW_LOCATION));
4684
4685 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004686 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004687 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004688 // 'notifyConnectionUnresponsive' should only be called once per connection
4689 mFakePolicy->assertNotifyAnrWasNotCalled();
4690 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004691 mWindow->consumeMotionDown();
4692 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4693 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4694 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004695 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004696 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004697 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004698}
4699
4700/**
4701 * If a window is processing a motion event, and then a key event comes in, the key event should
4702 * not to to the focused window until the motion is processed.
4703 *
4704 * Warning!!!
4705 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4706 * and the injection timeout that we specify when injecting the key.
4707 * We must have the injection timeout (10ms) be smaller than
4708 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4709 *
4710 * If that value changes, this test should also change.
4711 */
4712TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4713 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4714 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4715
4716 tapOnWindow();
4717 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4718 ASSERT_TRUE(downSequenceNum);
4719 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4720 ASSERT_TRUE(upSequenceNum);
4721 // Don't finish the events yet, and send a key
4722 // Injection will "succeed" because we will eventually give up and send the key to the focused
4723 // window even if motions are still being processed. But because the injection timeout is short,
4724 // we will receive INJECTION_TIMED_OUT as the result.
4725
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004726 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004727 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004728 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4729 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004730 // Key will not be sent to the window, yet, because the window is still processing events
4731 // and the key remains pending, waiting for the touch events to be processed
4732 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4733 ASSERT_FALSE(keySequenceNum);
4734
4735 std::this_thread::sleep_for(500ms);
4736 // if we wait long enough though, dispatcher will give up, and still send the key
4737 // to the focused window, even though we have not yet finished the motion event
4738 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4739 mWindow->finishEvent(*downSequenceNum);
4740 mWindow->finishEvent(*upSequenceNum);
4741}
4742
4743/**
4744 * If a window is processing a motion event, and then a key event comes in, the key event should
4745 * not go to the focused window until the motion is processed.
4746 * If then a new motion comes in, then the pending key event should be going to the currently
4747 * focused window right away.
4748 */
4749TEST_F(InputDispatcherSingleWindowAnr,
4750 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4751 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4752 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4753
4754 tapOnWindow();
4755 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4756 ASSERT_TRUE(downSequenceNum);
4757 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4758 ASSERT_TRUE(upSequenceNum);
4759 // Don't finish the events yet, and send a key
4760 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004761 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004762 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004763 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004764 // At this point, key is still pending, and should not be sent to the application yet.
4765 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4766 ASSERT_FALSE(keySequenceNum);
4767
4768 // Now tap down again. It should cause the pending key to go to the focused window right away.
4769 tapOnWindow();
4770 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4771 // the other events yet. We can finish events in any order.
4772 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4773 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4774 mWindow->consumeMotionDown();
4775 mWindow->consumeMotionUp();
4776 mWindow->assertNoEvents();
4777}
4778
4779class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4780 virtual void SetUp() override {
4781 InputDispatcherTest::SetUp();
4782
Chris Yea209fde2020-07-22 13:54:51 -07004783 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004784 mApplication->setDispatchingTimeout(10ms);
4785 mUnfocusedWindow =
4786 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4787 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4788 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4789 // window.
4790 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004791 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4792 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4793 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004794
4795 mFocusedWindow =
4796 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004797 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004798 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004799 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004800
4801 // Set focused application.
4802 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004803 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004804
4805 // Expect one focus window exist in display.
4806 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004807 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004808 mFocusedWindow->consumeFocusEvent(true);
4809 }
4810
4811 virtual void TearDown() override {
4812 InputDispatcherTest::TearDown();
4813
4814 mUnfocusedWindow.clear();
4815 mFocusedWindow.clear();
4816 }
4817
4818protected:
Chris Yea209fde2020-07-22 13:54:51 -07004819 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004820 sp<FakeWindowHandle> mUnfocusedWindow;
4821 sp<FakeWindowHandle> mFocusedWindow;
4822 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4823 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4824 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4825
4826 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4827
4828 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4829
4830private:
4831 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004832 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004833 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4834 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004835 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004836 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4837 location));
4838 }
4839};
4840
4841// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4842// should be ANR'd first.
4843TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004844 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004845 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4846 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004847 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004848 mFocusedWindow->consumeMotionDown();
4849 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4850 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4851 // We consumed all events, so no ANR
4852 ASSERT_TRUE(mDispatcher->waitForIdle());
4853 mFakePolicy->assertNotifyAnrWasNotCalled();
4854
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004855 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004856 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4857 FOCUSED_WINDOW_LOCATION));
4858 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4859 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004860
4861 const std::chrono::duration timeout =
4862 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004863 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004864 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4865 // sequence to make it consistent
4866 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004867 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004868 mFocusedWindow->consumeMotionDown();
4869 // This cancel is generated because the connection was unresponsive
4870 mFocusedWindow->consumeMotionCancel();
4871 mFocusedWindow->assertNoEvents();
4872 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004873 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004874 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004875 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004876}
4877
4878// If we have 2 windows with identical timeouts that are both unresponsive,
4879// it doesn't matter which order they should have ANR.
4880// But we should receive ANR for both.
4881TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4882 // Set the timeout for unfocused window to match the focused window
4883 mUnfocusedWindow->setDispatchingTimeout(10ms);
4884 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4885
4886 tapOnFocusedWindow();
4887 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004888 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4889 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004890
4891 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004892 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4893 mFocusedWindow->getToken() == anrConnectionToken2);
4894 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4895 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004896
4897 ASSERT_TRUE(mDispatcher->waitForIdle());
4898 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004899
4900 mFocusedWindow->consumeMotionDown();
4901 mFocusedWindow->consumeMotionUp();
4902 mUnfocusedWindow->consumeMotionOutside();
4903
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004904 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4905 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004906
4907 // Both applications should be marked as responsive, in any order
4908 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4909 mFocusedWindow->getToken() == responsiveToken2);
4910 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4911 mUnfocusedWindow->getToken() == responsiveToken2);
4912 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004913}
4914
4915// If a window is already not responding, the second tap on the same window should be ignored.
4916// We should also log an error to account for the dropped event (not tested here).
4917// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4918TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4919 tapOnFocusedWindow();
4920 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4921 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4922 // Receive the events, but don't respond
4923 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4924 ASSERT_TRUE(downEventSequenceNum);
4925 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4926 ASSERT_TRUE(upEventSequenceNum);
4927 const std::chrono::duration timeout =
4928 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004929 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004930
4931 // Tap once again
4932 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004933 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004934 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4935 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004936 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004937 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4938 FOCUSED_WINDOW_LOCATION));
4939 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4940 // valid touch target
4941 mUnfocusedWindow->assertNoEvents();
4942
4943 // Consume the first tap
4944 mFocusedWindow->finishEvent(*downEventSequenceNum);
4945 mFocusedWindow->finishEvent(*upEventSequenceNum);
4946 ASSERT_TRUE(mDispatcher->waitForIdle());
4947 // The second tap did not go to the focused window
4948 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004949 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004950 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004951 mFakePolicy->assertNotifyAnrWasNotCalled();
4952}
4953
4954// If you tap outside of all windows, there will not be ANR
4955TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004956 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004957 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4958 LOCATION_OUTSIDE_ALL_WINDOWS));
4959 ASSERT_TRUE(mDispatcher->waitForIdle());
4960 mFakePolicy->assertNotifyAnrWasNotCalled();
4961}
4962
4963// Since the focused window is paused, tapping on it should not produce any events
4964TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4965 mFocusedWindow->setPaused(true);
4966 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4967
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004968 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004969 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4970 FOCUSED_WINDOW_LOCATION));
4971
4972 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4973 ASSERT_TRUE(mDispatcher->waitForIdle());
4974 // Should not ANR because the window is paused, and touches shouldn't go to it
4975 mFakePolicy->assertNotifyAnrWasNotCalled();
4976
4977 mFocusedWindow->assertNoEvents();
4978 mUnfocusedWindow->assertNoEvents();
4979}
4980
4981/**
4982 * If a window is processing a motion event, and then a key event comes in, the key event should
4983 * not to to the focused window until the motion is processed.
4984 * If a different window becomes focused at this time, the key should go to that window instead.
4985 *
4986 * Warning!!!
4987 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4988 * and the injection timeout that we specify when injecting the key.
4989 * We must have the injection timeout (10ms) be smaller than
4990 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4991 *
4992 * If that value changes, this test should also change.
4993 */
4994TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4995 // Set a long ANR timeout to prevent it from triggering
4996 mFocusedWindow->setDispatchingTimeout(2s);
4997 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4998
4999 tapOnUnfocusedWindow();
5000 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5001 ASSERT_TRUE(downSequenceNum);
5002 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5003 ASSERT_TRUE(upSequenceNum);
5004 // Don't finish the events yet, and send a key
5005 // Injection will succeed because we will eventually give up and send the key to the focused
5006 // window even if motions are still being processed.
5007
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005008 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005009 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005010 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5011 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005012 // Key will not be sent to the window, yet, because the window is still processing events
5013 // and the key remains pending, waiting for the touch events to be processed
5014 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5015 ASSERT_FALSE(keySequenceNum);
5016
5017 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005018 mFocusedWindow->setFocusable(false);
5019 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005020 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005021 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005022
5023 // Focus events should precede the key events
5024 mUnfocusedWindow->consumeFocusEvent(true);
5025 mFocusedWindow->consumeFocusEvent(false);
5026
5027 // Finish the tap events, which should unblock dispatcher
5028 mUnfocusedWindow->finishEvent(*downSequenceNum);
5029 mUnfocusedWindow->finishEvent(*upSequenceNum);
5030
5031 // Now that all queues are cleared and no backlog in the connections, the key event
5032 // can finally go to the newly focused "mUnfocusedWindow".
5033 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5034 mFocusedWindow->assertNoEvents();
5035 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005036 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005037}
5038
5039// When the touch stream is split across 2 windows, and one of them does not respond,
5040// then ANR should be raised and the touch should be canceled for the unresponsive window.
5041// The other window should not be affected by that.
5042TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5043 // Touch Window 1
5044 NotifyMotionArgs motionArgs =
5045 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5046 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5047 mDispatcher->notifyMotion(&motionArgs);
5048 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5049 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5050
5051 // Touch Window 2
5052 int32_t actionPointerDown =
5053 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
5054
5055 motionArgs =
5056 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5057 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
5058 mDispatcher->notifyMotion(&motionArgs);
5059
5060 const std::chrono::duration timeout =
5061 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005062 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005063
5064 mUnfocusedWindow->consumeMotionDown();
5065 mFocusedWindow->consumeMotionDown();
5066 // Focused window may or may not receive ACTION_MOVE
5067 // But it should definitely receive ACTION_CANCEL due to the ANR
5068 InputEvent* event;
5069 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5070 ASSERT_TRUE(moveOrCancelSequenceNum);
5071 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5072 ASSERT_NE(nullptr, event);
5073 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5074 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5075 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5076 mFocusedWindow->consumeMotionCancel();
5077 } else {
5078 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5079 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005080 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005081 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005082
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005083 mUnfocusedWindow->assertNoEvents();
5084 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005085 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005086}
5087
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005088/**
5089 * If we have no focused window, and a key comes in, we start the ANR timer.
5090 * The focused application should add a focused window before the timer runs out to prevent ANR.
5091 *
5092 * If the user touches another application during this time, the key should be dropped.
5093 * Next, if a new focused window comes in, without toggling the focused application,
5094 * then no ANR should occur.
5095 *
5096 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5097 * but in some cases the policy may not update the focused application.
5098 */
5099TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5100 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5101 std::make_shared<FakeApplicationHandle>();
5102 focusedApplication->setDispatchingTimeout(60ms);
5103 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5104 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5105 mFocusedWindow->setFocusable(false);
5106
5107 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5108 mFocusedWindow->consumeFocusEvent(false);
5109
5110 // Send a key. The ANR timer should start because there is no focused window.
5111 // 'focusedApplication' will get blamed if this timer completes.
5112 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005113 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005114 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005115 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5116 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005117 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005118
5119 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5120 // then the injected touches won't cause the focused event to get dropped.
5121 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5122 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5123 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5124 // For this test, it means that the key would get delivered to the window once it becomes
5125 // focused.
5126 std::this_thread::sleep_for(10ms);
5127
5128 // Touch unfocused window. This should force the pending key to get dropped.
5129 NotifyMotionArgs motionArgs =
5130 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5131 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5132 mDispatcher->notifyMotion(&motionArgs);
5133
5134 // We do not consume the motion right away, because that would require dispatcher to first
5135 // process (== drop) the key event, and by that time, ANR will be raised.
5136 // Set the focused window first.
5137 mFocusedWindow->setFocusable(true);
5138 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5139 setFocusedWindow(mFocusedWindow);
5140 mFocusedWindow->consumeFocusEvent(true);
5141 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5142 // to another application. This could be a bug / behaviour in the policy.
5143
5144 mUnfocusedWindow->consumeMotionDown();
5145
5146 ASSERT_TRUE(mDispatcher->waitForIdle());
5147 // Should not ANR because we actually have a focused window. It was just added too slowly.
5148 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5149}
5150
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005151// These tests ensure we cannot send touch events to a window that's positioned behind a window
5152// that has feature NO_INPUT_CHANNEL.
5153// Layout:
5154// Top (closest to user)
5155// mNoInputWindow (above all windows)
5156// mBottomWindow
5157// Bottom (furthest from user)
5158class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5159 virtual void SetUp() override {
5160 InputDispatcherTest::SetUp();
5161
5162 mApplication = std::make_shared<FakeApplicationHandle>();
5163 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5164 "Window without input channel", ADISPLAY_ID_DEFAULT,
5165 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5166
chaviw3277faf2021-05-19 16:45:23 -05005167 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005168 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5169 // It's perfectly valid for this window to not have an associated input channel
5170
5171 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5172 ADISPLAY_ID_DEFAULT);
5173 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5174
5175 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5176 }
5177
5178protected:
5179 std::shared_ptr<FakeApplicationHandle> mApplication;
5180 sp<FakeWindowHandle> mNoInputWindow;
5181 sp<FakeWindowHandle> mBottomWindow;
5182};
5183
5184TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5185 PointF touchedPoint = {10, 10};
5186
5187 NotifyMotionArgs motionArgs =
5188 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5189 ADISPLAY_ID_DEFAULT, {touchedPoint});
5190 mDispatcher->notifyMotion(&motionArgs);
5191
5192 mNoInputWindow->assertNoEvents();
5193 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5194 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5195 // and therefore should prevent mBottomWindow from receiving touches
5196 mBottomWindow->assertNoEvents();
5197}
5198
5199/**
5200 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5201 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5202 */
5203TEST_F(InputDispatcherMultiWindowOcclusionTests,
5204 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5205 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5206 "Window with input channel and NO_INPUT_CHANNEL",
5207 ADISPLAY_ID_DEFAULT);
5208
chaviw3277faf2021-05-19 16:45:23 -05005209 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005210 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5211 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5212
5213 PointF touchedPoint = {10, 10};
5214
5215 NotifyMotionArgs motionArgs =
5216 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5217 ADISPLAY_ID_DEFAULT, {touchedPoint});
5218 mDispatcher->notifyMotion(&motionArgs);
5219
5220 mNoInputWindow->assertNoEvents();
5221 mBottomWindow->assertNoEvents();
5222}
5223
Vishnu Nair958da932020-08-21 17:12:37 -07005224class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5225protected:
5226 std::shared_ptr<FakeApplicationHandle> mApp;
5227 sp<FakeWindowHandle> mWindow;
5228 sp<FakeWindowHandle> mMirror;
5229
5230 virtual void SetUp() override {
5231 InputDispatcherTest::SetUp();
5232 mApp = std::make_shared<FakeApplicationHandle>();
5233 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5234 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5235 mWindow->getToken());
5236 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5237 mWindow->setFocusable(true);
5238 mMirror->setFocusable(true);
5239 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5240 }
5241};
5242
5243TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5244 // Request focus on a mirrored window
5245 setFocusedWindow(mMirror);
5246
5247 // window gets focused
5248 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005249 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5250 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005251 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5252}
5253
5254// A focused & mirrored window remains focused only if the window and its mirror are both
5255// focusable.
5256TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5257 setFocusedWindow(mMirror);
5258
5259 // window gets focused
5260 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005261 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5262 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005263 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005264 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5265 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005266 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5267
5268 mMirror->setFocusable(false);
5269 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5270
5271 // window loses focus since one of the windows associated with the token in not focusable
5272 mWindow->consumeFocusEvent(false);
5273
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005274 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5275 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005276 mWindow->assertNoEvents();
5277}
5278
5279// A focused & mirrored window remains focused until the window and its mirror both become
5280// invisible.
5281TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5282 setFocusedWindow(mMirror);
5283
5284 // window gets focused
5285 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005286 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5287 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005288 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005289 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5290 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005291 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5292
5293 mMirror->setVisible(false);
5294 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5295
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005296 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5297 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005298 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005299 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5300 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005301 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5302
5303 mWindow->setVisible(false);
5304 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5305
5306 // window loses focus only after all windows associated with the token become invisible.
5307 mWindow->consumeFocusEvent(false);
5308
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005309 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5310 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005311 mWindow->assertNoEvents();
5312}
5313
5314// A focused & mirrored window remains focused until both windows are removed.
5315TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5316 setFocusedWindow(mMirror);
5317
5318 // window gets focused
5319 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005320 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5321 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005322 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005323 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5324 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005325 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5326
5327 // single window is removed but the window token remains focused
5328 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5329
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005330 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5331 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005332 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005333 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5334 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005335 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5336
5337 // Both windows are removed
5338 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5339 mWindow->consumeFocusEvent(false);
5340
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005341 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5342 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005343 mWindow->assertNoEvents();
5344}
5345
5346// Focus request can be pending until one window becomes visible.
5347TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5348 // Request focus on an invisible mirror.
5349 mWindow->setVisible(false);
5350 mMirror->setVisible(false);
5351 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5352 setFocusedWindow(mMirror);
5353
5354 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005355 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005356 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005357 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005358
5359 mMirror->setVisible(true);
5360 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5361
5362 // window gets focused
5363 mWindow->consumeFocusEvent(true);
5364 // window gets the pending key event
5365 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5366}
Prabir Pradhan99987712020-11-10 18:43:05 -08005367
5368class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5369protected:
5370 std::shared_ptr<FakeApplicationHandle> mApp;
5371 sp<FakeWindowHandle> mWindow;
5372 sp<FakeWindowHandle> mSecondWindow;
5373
5374 void SetUp() override {
5375 InputDispatcherTest::SetUp();
5376 mApp = std::make_shared<FakeApplicationHandle>();
5377 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5378 mWindow->setFocusable(true);
5379 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5380 mSecondWindow->setFocusable(true);
5381
5382 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5383 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5384
5385 setFocusedWindow(mWindow);
5386 mWindow->consumeFocusEvent(true);
5387 }
5388
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005389 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5390 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005391 mDispatcher->notifyPointerCaptureChanged(&args);
5392 }
5393
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005394 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5395 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005396 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005397 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5398 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005399 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005400 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005401 }
5402};
5403
5404TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5405 // Ensure that capture cannot be obtained for unfocused windows.
5406 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5407 mFakePolicy->assertSetPointerCaptureNotCalled();
5408 mSecondWindow->assertNoEvents();
5409
5410 // Ensure that capture can be enabled from the focus window.
5411 requestAndVerifyPointerCapture(mWindow, true);
5412
5413 // Ensure that capture cannot be disabled from a window that does not have capture.
5414 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5415 mFakePolicy->assertSetPointerCaptureNotCalled();
5416
5417 // Ensure that capture can be disabled from the window with capture.
5418 requestAndVerifyPointerCapture(mWindow, false);
5419}
5420
5421TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005422 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005423
5424 setFocusedWindow(mSecondWindow);
5425
5426 // Ensure that the capture disabled event was sent first.
5427 mWindow->consumeCaptureEvent(false);
5428 mWindow->consumeFocusEvent(false);
5429 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005430 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005431
5432 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005433 notifyPointerCaptureChanged({});
5434 notifyPointerCaptureChanged(request);
5435 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005436 mWindow->assertNoEvents();
5437 mSecondWindow->assertNoEvents();
5438 mFakePolicy->assertSetPointerCaptureNotCalled();
5439}
5440
5441TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005442 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005443
5444 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005445 notifyPointerCaptureChanged({});
5446 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005447
5448 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005449 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005450 mWindow->consumeCaptureEvent(false);
5451 mWindow->assertNoEvents();
5452}
5453
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005454TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5455 requestAndVerifyPointerCapture(mWindow, true);
5456
5457 // The first window loses focus.
5458 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005459 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005460 mWindow->consumeCaptureEvent(false);
5461
5462 // Request Pointer Capture from the second window before the notification from InputReader
5463 // arrives.
5464 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005465 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005466
5467 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005468 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005469
5470 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005471 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005472
5473 mSecondWindow->consumeFocusEvent(true);
5474 mSecondWindow->consumeCaptureEvent(true);
5475}
5476
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005477TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5478 // App repeatedly enables and disables capture.
5479 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5480 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5481 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5482 mFakePolicy->assertSetPointerCaptureCalled(false);
5483 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5484 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5485
5486 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5487 // first request is now stale, this should do nothing.
5488 notifyPointerCaptureChanged(firstRequest);
5489 mWindow->assertNoEvents();
5490
5491 // InputReader notifies that the second request was enabled.
5492 notifyPointerCaptureChanged(secondRequest);
5493 mWindow->consumeCaptureEvent(true);
5494}
5495
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005496class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5497protected:
5498 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005499
5500 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5501 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5502
5503 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5504 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5505
5506 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5507 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5508 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5509 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5510 MAXIMUM_OBSCURING_OPACITY);
5511
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005512 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005513 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005514 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005515
5516 sp<FakeWindowHandle> mTouchWindow;
5517
5518 virtual void SetUp() override {
5519 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005520 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005521 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5522 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5523 }
5524
5525 virtual void TearDown() override {
5526 InputDispatcherTest::TearDown();
5527 mTouchWindow.clear();
5528 }
5529
chaviw3277faf2021-05-19 16:45:23 -05005530 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5531 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005532 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005533 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005534 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005535 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005536 return window;
5537 }
5538
5539 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5540 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5541 sp<FakeWindowHandle> window =
5542 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5543 // Generate an arbitrary PID based on the UID
5544 window->setOwnerInfo(1777 + (uid % 10000), uid);
5545 return window;
5546 }
5547
5548 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5549 NotifyMotionArgs args =
5550 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5551 ADISPLAY_ID_DEFAULT, points);
5552 mDispatcher->notifyMotion(&args);
5553 }
5554};
5555
5556TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005557 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005558 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005559 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005560
5561 touch();
5562
5563 mTouchWindow->assertNoEvents();
5564}
5565
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005566TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005567 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5568 const sp<FakeWindowHandle>& w =
5569 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5570 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5571
5572 touch();
5573
5574 mTouchWindow->assertNoEvents();
5575}
5576
5577TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005578 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5579 const sp<FakeWindowHandle>& w =
5580 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5581 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5582
5583 touch();
5584
5585 w->assertNoEvents();
5586}
5587
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005588TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005589 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5590 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005591
5592 touch();
5593
5594 mTouchWindow->consumeAnyMotionDown();
5595}
5596
5597TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005598 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005599 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005600 w->setFrame(Rect(0, 0, 50, 50));
5601 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005602
5603 touch({PointF{100, 100}});
5604
5605 mTouchWindow->consumeAnyMotionDown();
5606}
5607
5608TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005609 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005610 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005611 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5612
5613 touch();
5614
5615 mTouchWindow->consumeAnyMotionDown();
5616}
5617
5618TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5619 const sp<FakeWindowHandle>& w =
5620 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5621 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005622
5623 touch();
5624
5625 mTouchWindow->consumeAnyMotionDown();
5626}
5627
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005628TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5629 const sp<FakeWindowHandle>& w =
5630 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5631 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5632
5633 touch();
5634
5635 w->assertNoEvents();
5636}
5637
5638/**
5639 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5640 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5641 * window, the occluding window will still receive ACTION_OUTSIDE event.
5642 */
5643TEST_F(InputDispatcherUntrustedTouchesTest,
5644 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5645 const sp<FakeWindowHandle>& w =
5646 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005647 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005648 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5649
5650 touch();
5651
5652 w->consumeMotionOutside();
5653}
5654
5655TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5656 const sp<FakeWindowHandle>& w =
5657 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005658 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005659 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5660
5661 touch();
5662
5663 InputEvent* event = w->consume();
5664 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5665 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5666 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5667 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5668}
5669
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005670TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005671 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005672 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5673 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005674 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5675
5676 touch();
5677
5678 mTouchWindow->consumeAnyMotionDown();
5679}
5680
5681TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5682 const sp<FakeWindowHandle>& w =
5683 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5684 MAXIMUM_OBSCURING_OPACITY);
5685 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005686
5687 touch();
5688
5689 mTouchWindow->consumeAnyMotionDown();
5690}
5691
5692TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005693 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005694 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5695 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005696 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5697
5698 touch();
5699
5700 mTouchWindow->assertNoEvents();
5701}
5702
5703TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5704 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5705 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005706 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5707 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005708 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005709 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5710 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005711 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5712
5713 touch();
5714
5715 mTouchWindow->assertNoEvents();
5716}
5717
5718TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5719 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5720 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005721 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5722 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005723 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005724 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5725 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005726 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5727
5728 touch();
5729
5730 mTouchWindow->consumeAnyMotionDown();
5731}
5732
5733TEST_F(InputDispatcherUntrustedTouchesTest,
5734 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5735 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005736 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5737 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005738 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005739 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5740 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005741 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5742
5743 touch();
5744
5745 mTouchWindow->consumeAnyMotionDown();
5746}
5747
5748TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5749 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005750 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5751 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005752 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005753 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5754 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005755 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005756
5757 touch();
5758
5759 mTouchWindow->assertNoEvents();
5760}
5761
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005762TEST_F(InputDispatcherUntrustedTouchesTest,
5763 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5764 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005765 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5766 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005767 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005768 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5769 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005770 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5771
5772 touch();
5773
5774 mTouchWindow->assertNoEvents();
5775}
5776
5777TEST_F(InputDispatcherUntrustedTouchesTest,
5778 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5779 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005780 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5781 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005782 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005783 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5784 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005785 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5786
5787 touch();
5788
5789 mTouchWindow->consumeAnyMotionDown();
5790}
5791
5792TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5793 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005794 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5795 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005796 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5797
5798 touch();
5799
5800 mTouchWindow->consumeAnyMotionDown();
5801}
5802
5803TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5804 const sp<FakeWindowHandle>& w =
5805 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5806 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5807
5808 touch();
5809
5810 mTouchWindow->consumeAnyMotionDown();
5811}
5812
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005813TEST_F(InputDispatcherUntrustedTouchesTest,
5814 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5815 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5816 const sp<FakeWindowHandle>& w =
5817 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5818 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5819
5820 touch();
5821
5822 mTouchWindow->assertNoEvents();
5823}
5824
5825TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5826 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5827 const sp<FakeWindowHandle>& w =
5828 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5829 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5830
5831 touch();
5832
5833 mTouchWindow->consumeAnyMotionDown();
5834}
5835
5836TEST_F(InputDispatcherUntrustedTouchesTest,
5837 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5838 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5839 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005840 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5841 OPACITY_ABOVE_THRESHOLD);
5842 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5843
5844 touch();
5845
5846 mTouchWindow->consumeAnyMotionDown();
5847}
5848
5849TEST_F(InputDispatcherUntrustedTouchesTest,
5850 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5851 const sp<FakeWindowHandle>& w1 =
5852 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5853 OPACITY_BELOW_THRESHOLD);
5854 const sp<FakeWindowHandle>& w2 =
5855 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5856 OPACITY_BELOW_THRESHOLD);
5857 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5858
5859 touch();
5860
5861 mTouchWindow->assertNoEvents();
5862}
5863
5864/**
5865 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5866 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5867 * (which alone would result in allowing touches) does not affect the blocking behavior.
5868 */
5869TEST_F(InputDispatcherUntrustedTouchesTest,
5870 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5871 const sp<FakeWindowHandle>& wB =
5872 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5873 OPACITY_BELOW_THRESHOLD);
5874 const sp<FakeWindowHandle>& wC =
5875 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5876 OPACITY_BELOW_THRESHOLD);
5877 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5878
5879 touch();
5880
5881 mTouchWindow->assertNoEvents();
5882}
5883
5884/**
5885 * This test is testing that a window from a different UID but with same application token doesn't
5886 * block the touch. Apps can share the application token for close UI collaboration for example.
5887 */
5888TEST_F(InputDispatcherUntrustedTouchesTest,
5889 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5890 const sp<FakeWindowHandle>& w =
5891 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5892 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005893 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5894
5895 touch();
5896
5897 mTouchWindow->consumeAnyMotionDown();
5898}
5899
arthurhungb89ccb02020-12-30 16:19:01 +08005900class InputDispatcherDragTests : public InputDispatcherTest {
5901protected:
5902 std::shared_ptr<FakeApplicationHandle> mApp;
5903 sp<FakeWindowHandle> mWindow;
5904 sp<FakeWindowHandle> mSecondWindow;
5905 sp<FakeWindowHandle> mDragWindow;
5906
5907 void SetUp() override {
5908 InputDispatcherTest::SetUp();
5909 mApp = std::make_shared<FakeApplicationHandle>();
5910 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5911 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005912 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005913
5914 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5915 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005916 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005917
5918 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5919 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5920 }
5921
5922 // Start performing drag, we will create a drag window and transfer touch to it.
5923 void performDrag() {
5924 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5925 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5926 {50, 50}))
5927 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5928
5929 // Window should receive motion event.
5930 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5931
5932 // The drag window covers the entire display
5933 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5934 mDispatcher->setInputWindows(
5935 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5936
5937 // Transfer touch focus to the drag window
5938 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5939 true /* isDragDrop */);
5940 mWindow->consumeMotionCancel();
5941 mDragWindow->consumeMotionDown();
5942 }
arthurhung6d4bed92021-03-17 11:59:33 +08005943
5944 // Start performing drag, we will create a drag window and transfer touch to it.
5945 void performStylusDrag() {
5946 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5947 injectMotionEvent(mDispatcher,
5948 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5949 AINPUT_SOURCE_STYLUS)
5950 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5951 .pointer(PointerBuilder(0,
5952 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5953 .x(50)
5954 .y(50))
5955 .build()));
5956 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5957
5958 // The drag window covers the entire display
5959 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5960 mDispatcher->setInputWindows(
5961 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5962
5963 // Transfer touch focus to the drag window
5964 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5965 true /* isDragDrop */);
5966 mWindow->consumeMotionCancel();
5967 mDragWindow->consumeMotionDown();
5968 }
arthurhungb89ccb02020-12-30 16:19:01 +08005969};
5970
5971TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5972 performDrag();
5973
5974 // Move on window.
5975 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5976 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5977 ADISPLAY_ID_DEFAULT, {50, 50}))
5978 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5979 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5980 mWindow->consumeDragEvent(false, 50, 50);
5981 mSecondWindow->assertNoEvents();
5982
5983 // Move to another window.
5984 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5985 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5986 ADISPLAY_ID_DEFAULT, {150, 50}))
5987 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5988 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5989 mWindow->consumeDragEvent(true, 150, 50);
5990 mSecondWindow->consumeDragEvent(false, 50, 50);
5991
5992 // Move back to original window.
5993 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5994 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5995 ADISPLAY_ID_DEFAULT, {50, 50}))
5996 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5997 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5998 mWindow->consumeDragEvent(false, 50, 50);
5999 mSecondWindow->consumeDragEvent(true, -50, 50);
6000
6001 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6002 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6003 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6004 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6005 mWindow->assertNoEvents();
6006 mSecondWindow->assertNoEvents();
6007}
6008
arthurhungf452d0b2021-01-06 00:19:52 +08006009TEST_F(InputDispatcherDragTests, DragAndDrop) {
6010 performDrag();
6011
6012 // Move on window.
6013 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6014 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6015 ADISPLAY_ID_DEFAULT, {50, 50}))
6016 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6017 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6018 mWindow->consumeDragEvent(false, 50, 50);
6019 mSecondWindow->assertNoEvents();
6020
6021 // Move to another window.
6022 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6023 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6024 ADISPLAY_ID_DEFAULT, {150, 50}))
6025 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6026 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6027 mWindow->consumeDragEvent(true, 150, 50);
6028 mSecondWindow->consumeDragEvent(false, 50, 50);
6029
6030 // drop to another window.
6031 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6032 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6033 {150, 50}))
6034 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6035 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6036 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6037 mWindow->assertNoEvents();
6038 mSecondWindow->assertNoEvents();
6039}
6040
arthurhung6d4bed92021-03-17 11:59:33 +08006041TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6042 performStylusDrag();
6043
6044 // Move on window and keep button pressed.
6045 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6046 injectMotionEvent(mDispatcher,
6047 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6048 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6049 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6050 .x(50)
6051 .y(50))
6052 .build()))
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 and release button, expect to drop item.
6059 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6060 injectMotionEvent(mDispatcher,
6061 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6062 .buttonState(0)
6063 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6064 .x(150)
6065 .y(50))
6066 .build()))
6067 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6068 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6069 mWindow->assertNoEvents();
6070 mSecondWindow->assertNoEvents();
6071 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6072
6073 // nothing to the window.
6074 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6075 injectMotionEvent(mDispatcher,
6076 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6077 .buttonState(0)
6078 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6079 .x(150)
6080 .y(50))
6081 .build()))
6082 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6083 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6084 mWindow->assertNoEvents();
6085 mSecondWindow->assertNoEvents();
6086}
6087
Arthur Hung6d0571e2021-04-09 20:18:16 +08006088TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6089 performDrag();
6090
6091 // Set second window invisible.
6092 mSecondWindow->setVisible(false);
6093 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6094
6095 // Move on window.
6096 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6097 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6098 ADISPLAY_ID_DEFAULT, {50, 50}))
6099 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6100 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6101 mWindow->consumeDragEvent(false, 50, 50);
6102 mSecondWindow->assertNoEvents();
6103
6104 // Move to another window.
6105 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6106 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6107 ADISPLAY_ID_DEFAULT, {150, 50}))
6108 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6109 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6110 mWindow->consumeDragEvent(true, 150, 50);
6111 mSecondWindow->assertNoEvents();
6112
6113 // drop to another window.
6114 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6115 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6116 {150, 50}))
6117 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6118 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6119 mFakePolicy->assertDropTargetEquals(nullptr);
6120 mWindow->assertNoEvents();
6121 mSecondWindow->assertNoEvents();
6122}
6123
Vishnu Nair062a8672021-09-03 16:07:44 -07006124class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6125
6126TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6127 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6128 sp<FakeWindowHandle> window =
6129 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6130 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
6131 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6132 window->setFocusable(true);
6133 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {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, {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);
6160 window->assertNoEvents();
6161}
6162
6163TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
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 // With the flag cleared, the window should get input
6195 window->setInputFeatures({});
6196 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6197
6198 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6199 mDispatcher->notifyKey(&keyArgs);
6200 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6201
6202 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6203 ADISPLAY_ID_DEFAULT);
6204 mDispatcher->notifyMotion(&motionArgs);
6205 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6206 window->assertNoEvents();
6207}
6208
6209TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6210 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6211 std::make_shared<FakeApplicationHandle>();
6212 sp<FakeWindowHandle> obscuringWindow =
6213 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6214 ADISPLAY_ID_DEFAULT);
6215 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6216 obscuringWindow->setOwnerInfo(111, 111);
6217 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6218 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6219 sp<FakeWindowHandle> window =
6220 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6221 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6222 window->setOwnerInfo(222, 222);
6223 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6224 window->setFocusable(true);
6225 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6226 setFocusedWindow(window);
6227 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6228
6229 // With the flag set, window should not get any input
6230 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6231 mDispatcher->notifyKey(&keyArgs);
6232 window->assertNoEvents();
6233
6234 NotifyMotionArgs motionArgs =
6235 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6236 ADISPLAY_ID_DEFAULT);
6237 mDispatcher->notifyMotion(&motionArgs);
6238 window->assertNoEvents();
6239
6240 // When the window is no longer obscured because it went on top, it should get input
6241 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6242
6243 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6244 mDispatcher->notifyKey(&keyArgs);
6245 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6246
6247 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6248 ADISPLAY_ID_DEFAULT);
6249 mDispatcher->notifyMotion(&motionArgs);
6250 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6251 window->assertNoEvents();
6252}
6253
Antonio Kantekf16f2832021-09-28 04:39:20 +00006254class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6255protected:
6256 std::shared_ptr<FakeApplicationHandle> mApp;
6257 sp<FakeWindowHandle> mWindow;
6258 sp<FakeWindowHandle> mSecondWindow;
6259
6260 void SetUp() override {
6261 InputDispatcherTest::SetUp();
6262
6263 mApp = std::make_shared<FakeApplicationHandle>();
6264 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6265 mWindow->setFocusable(true);
6266 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6267 mSecondWindow->setFocusable(true);
6268
6269 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6270 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6271
6272 setFocusedWindow(mWindow);
6273 mWindow->consumeFocusEvent(true);
6274 }
6275
6276 void changeAndVerifyTouchMode(bool inTouchMode) {
6277 mDispatcher->setInTouchMode(inTouchMode);
6278 mWindow->consumeTouchModeEvent(inTouchMode);
6279 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6280 }
6281};
6282
6283TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
6284 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode);
6285}
6286
6287TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
6288 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode);
6289 mWindow->assertNoEvents();
6290 mSecondWindow->assertNoEvents();
6291}
6292
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006293class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6294public:
6295 sp<FakeWindowHandle> createSpy(const Flags<WindowInfo::Flag> flags) {
6296 std::shared_ptr<FakeApplicationHandle> application =
6297 std::make_shared<FakeApplicationHandle>();
6298 std::string name = "Fake Spy ";
6299 name += std::to_string(mSpyCount++);
6300 sp<FakeWindowHandle> spy =
6301 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
6302 spy->setInputFeatures(WindowInfo::Feature::SPY);
6303 spy->addFlags(flags);
6304 return spy;
6305 }
6306
6307 sp<FakeWindowHandle> createForeground() {
6308 std::shared_ptr<FakeApplicationHandle> application =
6309 std::make_shared<FakeApplicationHandle>();
6310 sp<FakeWindowHandle> window =
6311 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
6312 window->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
6313 return window;
6314 }
6315
6316private:
6317 int mSpyCount{0};
6318};
6319
6320/**
6321 * Input injection into a display with a spy window but no foreground windows should succeed.
6322 */
6323TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
6324 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6325 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6326
6327 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6328 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6329 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6330 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6331}
6332
6333/**
6334 * Verify the order in which different input windows receive events. The touched foreground window
6335 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6336 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6337 * receive events before ones belows it.
6338 *
6339 * Here, we set up a scenario with four windows in the following Z order from the top:
6340 * spy1, spy2, window, spy3.
6341 * We then inject an event and verify that the foreground "window" receives it first, followed by
6342 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6343 * window.
6344 */
6345TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6346 auto window = createForeground();
6347 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6348 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6349 auto spy3 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6350 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6351 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6352 const size_t numChannels = channels.size();
6353
6354 base::unique_fd epollFd(epoll_create1(0 /*flags*/));
6355 if (!epollFd.ok()) {
6356 FAIL() << "Failed to create epoll fd";
6357 }
6358
6359 for (size_t i = 0; i < numChannels; i++) {
6360 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6361 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6362 FAIL() << "Failed to add fd to epoll";
6363 }
6364 }
6365
6366 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6367 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6368 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6369
6370 std::vector<size_t> eventOrder;
6371 std::vector<struct epoll_event> events(numChannels);
6372 for (;;) {
6373 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6374 (100ms).count());
6375 if (nFds < 0) {
6376 FAIL() << "Failed to call epoll_wait";
6377 }
6378 if (nFds == 0) {
6379 break; // epoll_wait timed out
6380 }
6381 for (int i = 0; i < nFds; i++) {
6382 ASSERT_EQ(EPOLLIN, events[i].events);
6383 eventOrder.push_back(events[i].data.u64);
6384 channels[i]->consumeMotionDown();
6385 }
6386 }
6387
6388 // Verify the order in which the events were received.
6389 EXPECT_EQ(3u, eventOrder.size());
6390 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6391 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6392 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6393}
6394
6395/**
6396 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6397 */
6398TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6399 auto window = createForeground();
6400 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCHABLE);
6401 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6402
6403 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6404 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6405 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6406 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6407 spy->assertNoEvents();
6408}
6409
6410/**
6411 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6412 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6413 * to the window.
6414 */
6415TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6416 auto window = createForeground();
6417 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6418 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6419 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6420
6421 // Inject an event outside the spy window's touchable region.
6422 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6423 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6424 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6425 window->consumeMotionDown();
6426 spy->assertNoEvents();
6427 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6428 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6429 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6430 window->consumeMotionUp();
6431 spy->assertNoEvents();
6432
6433 // Inject an event inside the spy window's touchable region.
6434 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6435 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6436 {5, 10}))
6437 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6438 window->consumeMotionDown();
6439 spy->consumeMotionDown();
6440}
6441
6442/**
6443 * A spy window that is a modal window will receive gestures outside of its frame and touchable
6444 * region.
6445 */
6446TEST_F(InputDispatcherSpyWindowTest, ModalWindow) {
6447 auto window = createForeground();
6448 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6449 // This spy window does not have the NOT_TOUCH_MODAL flag set.
6450 spy->setFrame(Rect{0, 0, 20, 20});
6451 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6452
6453 // Inject an event outside the spy window's frame and touchable region.
6454 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6455 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6456 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6457 window->consumeMotionDown();
6458 spy->consumeMotionDown();
6459}
6460
6461/**
6462 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
6463 * flag.
6464 */
6465TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6466 auto window = createForeground();
6467 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
6468 spy->setFrame(Rect{0, 0, 20, 20});
6469 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6470
6471 // Inject an event outside the spy window's frame and touchable region.
6472 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6473 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6474 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6475 window->consumeMotionDown();
6476 spy->consumeMotionOutside();
6477}
6478
6479/**
6480 * When configured to block untrusted touches, events will not be dispatched to windows below a spy
6481 * window if it is not a trusted overly.
6482 */
6483TEST_F(InputDispatcherSpyWindowTest, BlockUntrustedTouches) {
6484 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
6485
6486 auto window = createForeground();
6487 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6488 window->setOwnerInfo(111, 111);
6489 spy->setOwnerInfo(222, 222);
6490 spy->setTouchOcclusionMode(TouchOcclusionMode::BLOCK_UNTRUSTED);
6491 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6492
6493 // Inject an event outside the spy window's frame and touchable region.
6494 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6495 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6496 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6497 spy->consumeMotionDown();
6498 window->assertNoEvents();
6499}
6500
6501/**
6502 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6503 * any other windows - including other spy windows - will also be cancelled.
6504 */
6505TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6506 auto window = createForeground();
6507 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6508 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6509 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6510
6511 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6512 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6513 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6514 window->consumeMotionDown();
6515 spy1->consumeMotionDown();
6516 spy2->consumeMotionDown();
6517
6518 // Pilfer pointers from the second spy window.
6519 mDispatcher->pilferPointers(spy2->getToken());
6520 spy2->assertNoEvents();
6521 spy1->consumeMotionCancel();
6522 window->consumeMotionCancel();
6523
6524 // The rest of the gesture should only be sent to the second spy window.
6525 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6526 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6527 ADISPLAY_ID_DEFAULT))
6528 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6529 spy2->consumeMotionMove();
6530 spy1->assertNoEvents();
6531 window->assertNoEvents();
6532}
6533
6534/**
6535 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6536 * pointers that are down within its bounds.
6537 */
6538TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6539 auto windowLeft = createForeground();
6540 windowLeft->setFrame({0, 0, 100, 200});
6541 auto windowRight = createForeground();
6542 windowRight->setFrame({100, 0, 200, 200});
6543 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6544 spy->setFrame({0, 0, 200, 200});
6545 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6546
6547 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6548 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6549 {50, 50}))
6550 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6551 windowLeft->consumeMotionDown();
6552 spy->consumeMotionDown();
6553
6554 const MotionEvent secondFingerDownEvent =
6555 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6556 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6557 AINPUT_SOURCE_TOUCHSCREEN)
6558 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6559 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6560 .pointer(
6561 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6562 .build();
6563 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6564 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6565 InputEventInjectionSync::WAIT_FOR_RESULT))
6566 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6567 windowRight->consumeMotionDown();
6568 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6569}
6570
6571/**
6572 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6573 * the spy should receive the second pointer with ACTION_DOWN.
6574 */
6575TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6576 auto window = createForeground();
6577 window->setFrame({0, 0, 200, 200});
6578 auto spyRight = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6579 spyRight->setFrame({100, 0, 200, 200});
6580 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6581
6582 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6583 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6584 {50, 50}))
6585 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6586 window->consumeMotionDown();
6587 spyRight->assertNoEvents();
6588
6589 const MotionEvent secondFingerDownEvent =
6590 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6591 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6592 AINPUT_SOURCE_TOUCHSCREEN)
6593 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6594 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6595 .pointer(
6596 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6597 .build();
6598 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6599 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6600 InputEventInjectionSync::WAIT_FOR_RESULT))
6601 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6602 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6603 spyRight->consumeMotionDown();
6604}
6605
Prabir Pradhand65552b2021-10-07 11:23:50 -07006606class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6607public:
6608 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6609 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6610 std::make_shared<FakeApplicationHandle>();
6611 sp<FakeWindowHandle> overlay =
6612 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6613 ADISPLAY_ID_DEFAULT);
6614 overlay->setFocusable(false);
6615 overlay->setOwnerInfo(111, 111);
6616 overlay->setFlags(WindowInfo::Flag::NOT_TOUCHABLE | WindowInfo::Flag::SPLIT_TOUCH);
6617 overlay->setInputFeatures(WindowInfo::Feature::INTERCEPTS_STYLUS);
6618 overlay->setTrustedOverlay(true);
6619
6620 std::shared_ptr<FakeApplicationHandle> application =
6621 std::make_shared<FakeApplicationHandle>();
6622 sp<FakeWindowHandle> window =
6623 new FakeWindowHandle(application, mDispatcher, "Application window",
6624 ADISPLAY_ID_DEFAULT);
6625 window->setFocusable(true);
6626 window->setOwnerInfo(222, 222);
6627 window->setFlags(WindowInfo::Flag::SPLIT_TOUCH);
6628
6629 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6630 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6631 setFocusedWindow(window);
6632 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6633 return {std::move(overlay), std::move(window)};
6634 }
6635
6636 void sendFingerEvent(int32_t action) {
6637 NotifyMotionArgs motionArgs =
6638 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6639 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6640 mDispatcher->notifyMotion(&motionArgs);
6641 }
6642
6643 void sendStylusEvent(int32_t action) {
6644 NotifyMotionArgs motionArgs =
6645 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6646 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6647 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6648 mDispatcher->notifyMotion(&motionArgs);
6649 }
6650};
6651
6652TEST_F(InputDispatcherStylusInterceptorTest, UntrustedOverlay_AbortsDispatcher) {
6653 auto [overlay, window] = setupStylusOverlayScenario();
6654 overlay->setTrustedOverlay(false);
6655 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6656 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6657 ".* not a trusted overlay");
6658}
6659
6660TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6661 auto [overlay, window] = setupStylusOverlayScenario();
6662 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6663
6664 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6665 overlay->consumeMotionDown();
6666 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6667 overlay->consumeMotionUp();
6668
6669 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6670 window->consumeMotionDown();
6671 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6672 window->consumeMotionUp();
6673
6674 overlay->assertNoEvents();
6675 window->assertNoEvents();
6676}
6677
6678TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6679 auto [overlay, window] = setupStylusOverlayScenario();
6680 overlay->setInputFeatures(overlay->getInfo()->inputFeatures | WindowInfo::Feature::SPY);
6681 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6682
6683 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6684 overlay->consumeMotionDown();
6685 window->consumeMotionDown();
6686 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6687 overlay->consumeMotionUp();
6688 window->consumeMotionUp();
6689
6690 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6691 window->consumeMotionDown();
6692 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6693 window->consumeMotionUp();
6694
6695 overlay->assertNoEvents();
6696 window->assertNoEvents();
6697}
6698
Garfield Tane84e6f92019-08-29 17:28:41 -07006699} // namespace android::inputdispatcher