blob: 497a6b9f3a56f91b28a7ade063867076c6c74b01 [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];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800561 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 pointerProperties[i].clear();
563 pointerProperties[i].id = i;
564 pointerCoords[i].clear();
565 }
566
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800567 // Some constants commonly used below
568 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
569 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
570 constexpr int32_t metaState = AMETA_NONE;
571 constexpr MotionClassification classification = MotionClassification::NONE;
572
chaviw9eaa22c2020-07-01 16:21:27 -0700573 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800574 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800575 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700576 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
577 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700578 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
579 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700580 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800581 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700582 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800583 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800584 << "Should reject motion events with undefined action.";
585
586 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800587 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
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
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002189// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2190// event should be treated as being in the logical display space.
2191TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2192 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2193
2194 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2195 ui::Transform injectedEventTransform;
2196 injectedEventTransform.set(matrix);
2197 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2198 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2199
2200 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2201 .displayId(ADISPLAY_ID_DEFAULT)
2202 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2203 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2204 .x(untransformedPoint.x)
2205 .y(untransformedPoint.y))
2206 .build();
2207 event.transform(matrix);
2208
2209 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2210 InputEventInjectionSync::WAIT_FOR_RESULT);
2211
2212 firstWindow->consumeMotionDown();
2213 secondWindow->assertNoEvents();
2214}
2215
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002216TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2217 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2218
2219 // Send down to the second window.
2220 NotifyMotionArgs downMotionArgs =
2221 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2222 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2223 mDispatcher->notifyMotion(&downMotionArgs);
2224
2225 firstWindow->assertNoEvents();
2226 const MotionEvent* event = secondWindow->consumeMotion();
2227 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2228
2229 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2230 EXPECT_EQ(300, event->getRawX(0));
2231 EXPECT_EQ(880, event->getRawY(0));
2232
2233 // Ensure that the x and y values are in the window's coordinate space.
2234 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2235 // the logical display space. This will be the origin of the window space.
2236 EXPECT_EQ(100, event->getX(0));
2237 EXPECT_EQ(80, event->getY(0));
2238}
2239
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002240using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2241 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002242
2243class TransferTouchFixture : public InputDispatcherTest,
2244 public ::testing::WithParamInterface<TransferFunction> {};
2245
2246TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002247 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002248
2249 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002250 sp<FakeWindowHandle> firstWindow =
2251 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2252 sp<FakeWindowHandle> secondWindow =
2253 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002254
2255 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002256 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002257
2258 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002259 NotifyMotionArgs downMotionArgs =
2260 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2261 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002262 mDispatcher->notifyMotion(&downMotionArgs);
2263 // Only the first window should get the down event
2264 firstWindow->consumeMotionDown();
2265 secondWindow->assertNoEvents();
2266
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002267 // Transfer touch to the second window
2268 TransferFunction f = GetParam();
2269 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2270 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002271 // The first window gets cancel and the second gets down
2272 firstWindow->consumeMotionCancel();
2273 secondWindow->consumeMotionDown();
2274
2275 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002276 NotifyMotionArgs upMotionArgs =
2277 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2278 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002279 mDispatcher->notifyMotion(&upMotionArgs);
2280 // The first window gets no events and the second gets up
2281 firstWindow->assertNoEvents();
2282 secondWindow->consumeMotionUp();
2283}
2284
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002285TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002286 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002287
2288 PointF touchPoint = {10, 10};
2289
2290 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002291 sp<FakeWindowHandle> firstWindow =
2292 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2293 sp<FakeWindowHandle> secondWindow =
2294 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002295
2296 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002297 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002298
2299 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002300 NotifyMotionArgs downMotionArgs =
2301 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2302 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002303 mDispatcher->notifyMotion(&downMotionArgs);
2304 // Only the first window should get the down event
2305 firstWindow->consumeMotionDown();
2306 secondWindow->assertNoEvents();
2307
2308 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002309 NotifyMotionArgs pointerDownMotionArgs =
2310 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2311 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2312 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2313 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002314 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2315 // Only the first window should get the pointer down event
2316 firstWindow->consumeMotionPointerDown(1);
2317 secondWindow->assertNoEvents();
2318
2319 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002320 TransferFunction f = GetParam();
2321 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2322 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002323 // The first window gets cancel and the second gets down and pointer down
2324 firstWindow->consumeMotionCancel();
2325 secondWindow->consumeMotionDown();
2326 secondWindow->consumeMotionPointerDown(1);
2327
2328 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002329 NotifyMotionArgs pointerUpMotionArgs =
2330 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2331 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2332 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2333 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002334 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2335 // The first window gets nothing and the second gets pointer up
2336 firstWindow->assertNoEvents();
2337 secondWindow->consumeMotionPointerUp(1);
2338
2339 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002340 NotifyMotionArgs upMotionArgs =
2341 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2342 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002343 mDispatcher->notifyMotion(&upMotionArgs);
2344 // The first window gets nothing and the second gets up
2345 firstWindow->assertNoEvents();
2346 secondWindow->consumeMotionUp();
2347}
2348
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002349// For the cases of single pointer touch and two pointers non-split touch, the api's
2350// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2351// for the case where there are multiple pointers split across several windows.
2352INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2353 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002354 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2355 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002356 return dispatcher->transferTouch(destChannelToken);
2357 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002358 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2359 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002360 return dispatcher->transferTouchFocus(from, to,
2361 false /*isDragAndDrop*/);
2362 }));
2363
Svet Ganov5d3bc372020-01-26 23:11:07 -08002364TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002365 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002366
2367 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002368 sp<FakeWindowHandle> firstWindow =
2369 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002370 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002371 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002372
2373 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002374 sp<FakeWindowHandle> secondWindow =
2375 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002376 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002377 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002378
2379 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002380 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002381
2382 PointF pointInFirst = {300, 200};
2383 PointF pointInSecond = {300, 600};
2384
2385 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002386 NotifyMotionArgs firstDownMotionArgs =
2387 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2388 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002389 mDispatcher->notifyMotion(&firstDownMotionArgs);
2390 // Only the first window should get the down event
2391 firstWindow->consumeMotionDown();
2392 secondWindow->assertNoEvents();
2393
2394 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002395 NotifyMotionArgs secondDownMotionArgs =
2396 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2397 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2398 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2399 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002400 mDispatcher->notifyMotion(&secondDownMotionArgs);
2401 // The first window gets a move and the second a down
2402 firstWindow->consumeMotionMove();
2403 secondWindow->consumeMotionDown();
2404
2405 // Transfer touch focus to the second window
2406 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2407 // The first window gets cancel and the new gets pointer down (it already saw down)
2408 firstWindow->consumeMotionCancel();
2409 secondWindow->consumeMotionPointerDown(1);
2410
2411 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002412 NotifyMotionArgs pointerUpMotionArgs =
2413 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2414 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2415 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2416 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002417 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2418 // The first window gets nothing and the second gets pointer up
2419 firstWindow->assertNoEvents();
2420 secondWindow->consumeMotionPointerUp(1);
2421
2422 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002423 NotifyMotionArgs upMotionArgs =
2424 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2425 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002426 mDispatcher->notifyMotion(&upMotionArgs);
2427 // The first window gets nothing and the second gets up
2428 firstWindow->assertNoEvents();
2429 secondWindow->consumeMotionUp();
2430}
2431
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002432// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2433// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2434// touch is not supported, so the touch should continue on those windows and the transferred-to
2435// window should get nothing.
2436TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2437 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2438
2439 // Create a non touch modal window that supports split touch
2440 sp<FakeWindowHandle> firstWindow =
2441 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2442 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002443 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002444
2445 // Create a non touch modal window that supports split touch
2446 sp<FakeWindowHandle> secondWindow =
2447 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2448 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002449 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002450
2451 // Add the windows to the dispatcher
2452 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2453
2454 PointF pointInFirst = {300, 200};
2455 PointF pointInSecond = {300, 600};
2456
2457 // Send down to the first window
2458 NotifyMotionArgs firstDownMotionArgs =
2459 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2460 ADISPLAY_ID_DEFAULT, {pointInFirst});
2461 mDispatcher->notifyMotion(&firstDownMotionArgs);
2462 // Only the first window should get the down event
2463 firstWindow->consumeMotionDown();
2464 secondWindow->assertNoEvents();
2465
2466 // Send down to the second window
2467 NotifyMotionArgs secondDownMotionArgs =
2468 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2469 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2470 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2471 {pointInFirst, pointInSecond});
2472 mDispatcher->notifyMotion(&secondDownMotionArgs);
2473 // The first window gets a move and the second a down
2474 firstWindow->consumeMotionMove();
2475 secondWindow->consumeMotionDown();
2476
2477 // Transfer touch focus to the second window
2478 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2479 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2480 ASSERT_FALSE(transferred);
2481 firstWindow->assertNoEvents();
2482 secondWindow->assertNoEvents();
2483
2484 // The rest of the dispatch should proceed as normal
2485 // Send pointer up to the second window
2486 NotifyMotionArgs pointerUpMotionArgs =
2487 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2488 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2489 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2490 {pointInFirst, pointInSecond});
2491 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2492 // The first window gets MOVE and the second gets pointer up
2493 firstWindow->consumeMotionMove();
2494 secondWindow->consumeMotionUp();
2495
2496 // Send up event to the first window
2497 NotifyMotionArgs upMotionArgs =
2498 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2499 ADISPLAY_ID_DEFAULT);
2500 mDispatcher->notifyMotion(&upMotionArgs);
2501 // The first window gets nothing and the second gets up
2502 firstWindow->consumeMotionUp();
2503 secondWindow->assertNoEvents();
2504}
2505
Arthur Hungabbb9d82021-09-01 14:52:30 +00002506// This case will create two windows and one mirrored window on the default display and mirror
2507// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2508// the windows info of second display before default display.
2509TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2510 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2511 sp<FakeWindowHandle> firstWindowInPrimary =
2512 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2513 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2514 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2515 sp<FakeWindowHandle> secondWindowInPrimary =
2516 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2517 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2518 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2519
2520 sp<FakeWindowHandle> mirrorWindowInPrimary =
2521 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2522 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2523 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2524
2525 sp<FakeWindowHandle> firstWindowInSecondary =
2526 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2527 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2528 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2529
2530 sp<FakeWindowHandle> secondWindowInSecondary =
2531 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2532 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2533 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2534
2535 // Update window info, let it find window handle of second display first.
2536 mDispatcher->setInputWindows(
2537 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2538 {ADISPLAY_ID_DEFAULT,
2539 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2540
2541 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2542 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2543 {50, 50}))
2544 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2545
2546 // Window should receive motion event.
2547 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2548
2549 // Transfer touch focus
2550 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2551 secondWindowInPrimary->getToken()));
2552 // The first window gets cancel.
2553 firstWindowInPrimary->consumeMotionCancel();
2554 secondWindowInPrimary->consumeMotionDown();
2555
2556 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2557 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2558 ADISPLAY_ID_DEFAULT, {150, 50}))
2559 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2560 firstWindowInPrimary->assertNoEvents();
2561 secondWindowInPrimary->consumeMotionMove();
2562
2563 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2564 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2565 {150, 50}))
2566 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2567 firstWindowInPrimary->assertNoEvents();
2568 secondWindowInPrimary->consumeMotionUp();
2569}
2570
2571// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2572// 'transferTouch' api.
2573TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2574 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2575 sp<FakeWindowHandle> firstWindowInPrimary =
2576 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2577 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2578 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2579 sp<FakeWindowHandle> secondWindowInPrimary =
2580 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2581 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2582 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2583
2584 sp<FakeWindowHandle> mirrorWindowInPrimary =
2585 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2586 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2587 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2588
2589 sp<FakeWindowHandle> firstWindowInSecondary =
2590 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2591 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2592 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2593
2594 sp<FakeWindowHandle> secondWindowInSecondary =
2595 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2596 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2597 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2598
2599 // Update window info, let it find window handle of second display first.
2600 mDispatcher->setInputWindows(
2601 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2602 {ADISPLAY_ID_DEFAULT,
2603 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2604
2605 // Touch on second display.
2606 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2607 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2608 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2609
2610 // Window should receive motion event.
2611 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2612
2613 // Transfer touch focus
2614 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2615
2616 // The first window gets cancel.
2617 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2618 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2619
2620 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2621 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2622 SECOND_DISPLAY_ID, {150, 50}))
2623 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2624 firstWindowInPrimary->assertNoEvents();
2625 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2626
2627 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2628 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2629 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2630 firstWindowInPrimary->assertNoEvents();
2631 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2632}
2633
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002634TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002635 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002636 sp<FakeWindowHandle> window =
2637 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2638
Vishnu Nair47074b82020-08-14 11:54:47 -07002639 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002640 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002641 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002642
2643 window->consumeFocusEvent(true);
2644
2645 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2646 mDispatcher->notifyKey(&keyArgs);
2647
2648 // Window should receive key down event.
2649 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2650}
2651
2652TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002653 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002654 sp<FakeWindowHandle> window =
2655 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2656
Arthur Hung72d8dc32020-03-28 00:48:39 +00002657 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002658
2659 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2660 mDispatcher->notifyKey(&keyArgs);
2661 mDispatcher->waitForIdle();
2662
2663 window->assertNoEvents();
2664}
2665
2666// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2667TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002668 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002669 sp<FakeWindowHandle> window =
2670 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2671
Arthur Hung72d8dc32020-03-28 00:48:39 +00002672 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002673
2674 // Send key
2675 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2676 mDispatcher->notifyKey(&keyArgs);
2677 // Send motion
2678 NotifyMotionArgs motionArgs =
2679 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2680 ADISPLAY_ID_DEFAULT);
2681 mDispatcher->notifyMotion(&motionArgs);
2682
2683 // Window should receive only the motion event
2684 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2685 window->assertNoEvents(); // Key event or focus event will not be received
2686}
2687
arthurhungea3f4fc2020-12-21 23:18:53 +08002688TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2689 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2690
2691 // Create first non touch modal window that supports split touch
2692 sp<FakeWindowHandle> firstWindow =
2693 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2694 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002695 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002696
2697 // Create second non touch modal window that supports split touch
2698 sp<FakeWindowHandle> secondWindow =
2699 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2700 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002701 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002702
2703 // Add the windows to the dispatcher
2704 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2705
2706 PointF pointInFirst = {300, 200};
2707 PointF pointInSecond = {300, 600};
2708
2709 // Send down to the first window
2710 NotifyMotionArgs firstDownMotionArgs =
2711 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2712 ADISPLAY_ID_DEFAULT, {pointInFirst});
2713 mDispatcher->notifyMotion(&firstDownMotionArgs);
2714 // Only the first window should get the down event
2715 firstWindow->consumeMotionDown();
2716 secondWindow->assertNoEvents();
2717
2718 // Send down to the second window
2719 NotifyMotionArgs secondDownMotionArgs =
2720 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2721 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2722 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2723 {pointInFirst, pointInSecond});
2724 mDispatcher->notifyMotion(&secondDownMotionArgs);
2725 // The first window gets a move and the second a down
2726 firstWindow->consumeMotionMove();
2727 secondWindow->consumeMotionDown();
2728
2729 // Send pointer cancel to the second window
2730 NotifyMotionArgs pointerUpMotionArgs =
2731 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2732 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2733 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2734 {pointInFirst, pointInSecond});
2735 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2736 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2737 // The first window gets move and the second gets cancel.
2738 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2739 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2740
2741 // Send up event.
2742 NotifyMotionArgs upMotionArgs =
2743 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2744 ADISPLAY_ID_DEFAULT);
2745 mDispatcher->notifyMotion(&upMotionArgs);
2746 // The first window gets up and the second gets nothing.
2747 firstWindow->consumeMotionUp();
2748 secondWindow->assertNoEvents();
2749}
2750
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002751TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2752 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2753
2754 sp<FakeWindowHandle> window =
2755 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2756 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2757 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2758 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2759 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2760
2761 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2762 window->assertNoEvents();
2763 mDispatcher->waitForIdle();
2764}
2765
chaviwd1c23182019-12-20 18:44:56 -08002766class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002767public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002768 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002769 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002770 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002771 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002772 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002773 }
2774
chaviwd1c23182019-12-20 18:44:56 -08002775 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2776
2777 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2778 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2779 expectedDisplayId, expectedFlags);
2780 }
2781
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002782 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2783
2784 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2785
chaviwd1c23182019-12-20 18:44:56 -08002786 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2787 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2788 expectedDisplayId, expectedFlags);
2789 }
2790
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002791 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2792 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2793 expectedDisplayId, expectedFlags);
2794 }
2795
chaviwd1c23182019-12-20 18:44:56 -08002796 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2797 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2798 expectedDisplayId, expectedFlags);
2799 }
2800
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002801 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2802 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2803 expectedDisplayId, expectedFlags);
2804 }
2805
Arthur Hungfbfa5722021-11-16 02:45:54 +00002806 void consumeMotionPointerDown(int32_t pointerIdx) {
2807 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2808 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2809 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2810 0 /*expectedFlags*/);
2811 }
2812
Evan Rosky84f07f02021-04-16 10:42:42 -07002813 MotionEvent* consumeMotion() {
2814 InputEvent* event = mInputReceiver->consume();
2815 if (!event) {
2816 ADD_FAILURE() << "No event was produced";
2817 return nullptr;
2818 }
2819 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2820 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2821 return nullptr;
2822 }
2823 return static_cast<MotionEvent*>(event);
2824 }
2825
chaviwd1c23182019-12-20 18:44:56 -08002826 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2827
2828private:
2829 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002830};
2831
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002832/**
2833 * Two entities that receive touch: A window, and a global monitor.
2834 * The touch goes to the window, and then the window disappears.
2835 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2836 * for the monitor, as well.
2837 * 1. foregroundWindow
2838 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2839 */
2840TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_GlobalMonitorTouchIsCanceled) {
2841 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2842 sp<FakeWindowHandle> window =
2843 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2844
2845 FakeMonitorReceiver monitor =
2846 FakeMonitorReceiver(mDispatcher, "GlobalMonitor", ADISPLAY_ID_DEFAULT,
2847 false /*isGestureMonitor*/);
2848
2849 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2850 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2851 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2852 {100, 200}))
2853 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2854
2855 // Both the foreground window and the global monitor should receive the touch down
2856 window->consumeMotionDown();
2857 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2858
2859 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2860 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2861 ADISPLAY_ID_DEFAULT, {110, 200}))
2862 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2863
2864 window->consumeMotionMove();
2865 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2866
2867 // Now the foreground window goes away
2868 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2869 window->consumeMotionCancel();
2870 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2871
2872 // If more events come in, there will be no more foreground window to send them to. This will
2873 // cause a cancel for the monitor, as well.
2874 ASSERT_EQ(InputEventInjectionResult::FAILED,
2875 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2876 ADISPLAY_ID_DEFAULT, {120, 200}))
2877 << "Injection should fail because the window was removed";
2878 window->assertNoEvents();
2879 // Global monitor now gets the cancel
2880 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2881}
2882
Michael Wright3a240c42019-12-10 20:53:41 +00002883// Tests for gesture monitors
2884TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002885 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002886 sp<FakeWindowHandle> window =
2887 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002888 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002889
chaviwd1c23182019-12-20 18:44:56 -08002890 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2891 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002892
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002893 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002894 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002895 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002896 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002897 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002898}
2899
2900TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002901 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002902 sp<FakeWindowHandle> window =
2903 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2904
2905 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002906 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002907
Arthur Hung72d8dc32020-03-28 00:48:39 +00002908 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002909 setFocusedWindow(window);
2910
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002911 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002912
chaviwd1c23182019-12-20 18:44:56 -08002913 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2914 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002915
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002916 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2917 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002918 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002919 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002920}
2921
2922TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002923 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002924 sp<FakeWindowHandle> window =
2925 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002926 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002927
chaviwd1c23182019-12-20 18:44:56 -08002928 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2929 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002930
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002931 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002932 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002933 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002934 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002935 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002936
2937 window->releaseChannel();
2938
chaviwd1c23182019-12-20 18:44:56 -08002939 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002940
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002941 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002942 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002943 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002944 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002945}
2946
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002947TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2948 FakeMonitorReceiver monitor =
2949 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2950 true /*isGestureMonitor*/);
2951
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002952 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002953 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2954 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2955 ASSERT_TRUE(consumeSeq);
2956
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002957 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002958 monitor.finishEvent(*consumeSeq);
2959 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002960 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002961}
2962
Evan Rosky84f07f02021-04-16 10:42:42 -07002963// Tests for gesture monitors
2964TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2965 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2966 sp<FakeWindowHandle> window =
2967 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2968 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2969 window->setWindowOffset(20, 40);
2970 window->setWindowTransform(0, 1, -1, 0);
2971
2972 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2973 true /*isGestureMonitor*/);
2974
2975 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2976 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2977 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2978 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2979 MotionEvent* event = monitor.consumeMotion();
2980 // Even though window has transform, gesture monitor must not.
2981 ASSERT_EQ(ui::Transform(), event->getTransform());
2982}
2983
Arthur Hungb3307ee2021-10-14 10:57:37 +00002984TEST_F(InputDispatcherTest, GestureMonitor_NoWindow) {
2985 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2986 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2987 true /*isGestureMonitor*/);
2988
2989 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2990 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2991 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2992 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2993}
2994
chaviw81e2bb92019-12-18 15:03:51 -08002995TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002996 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002997 sp<FakeWindowHandle> window =
2998 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2999
Arthur Hung72d8dc32020-03-28 00:48:39 +00003000 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003001
3002 NotifyMotionArgs motionArgs =
3003 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3004 ADISPLAY_ID_DEFAULT);
3005
3006 mDispatcher->notifyMotion(&motionArgs);
3007 // Window should receive motion down event.
3008 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3009
3010 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003011 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003012 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3013 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3014 motionArgs.pointerCoords[0].getX() - 10);
3015
3016 mDispatcher->notifyMotion(&motionArgs);
3017 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3018 0 /*expectedFlags*/);
3019}
3020
Arthur Hungfbfa5722021-11-16 02:45:54 +00003021TEST_F(InputDispatcherTest, GestureMonitor_SplitIfNoWindowTouched) {
3022 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
3023 true /*isGestureMonitor*/);
3024
3025 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3026 // Create a non touch modal window that supports split touch
3027 sp<FakeWindowHandle> window =
3028 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3029 window->setFrame(Rect(0, 0, 100, 100));
3030 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
3031 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3032
3033 // First finger down, no window touched.
3034 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3035 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3036 {100, 200}))
3037 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3038 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3039 window->assertNoEvents();
3040
3041 // Second finger down on window, the window should receive touch down.
3042 const MotionEvent secondFingerDownEvent =
3043 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
3044 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
3045 AINPUT_SOURCE_TOUCHSCREEN)
3046 .displayId(ADISPLAY_ID_DEFAULT)
3047 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3048 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3049 .x(100)
3050 .y(200))
3051 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3052 .build();
3053 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3054 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
3055 InputEventInjectionSync::WAIT_FOR_RESULT))
3056 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3057
3058 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3059 monitor.consumeMotionPointerDown(1 /* pointerIndex */);
3060}
3061
3062TEST_F(InputDispatcherTest, GestureMonitor_NoSplitAfterPilfer) {
3063 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
3064 true /*isGestureMonitor*/);
3065
3066 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3067 // Create a non touch modal window that supports split touch
3068 sp<FakeWindowHandle> window =
3069 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3070 window->setFrame(Rect(0, 0, 100, 100));
3071 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
3072 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3073
3074 // First finger down, no window touched.
3075 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3076 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3077 {100, 200}))
3078 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3079 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3080 window->assertNoEvents();
3081
3082 // Gesture monitor pilfer the pointers.
3083 mDispatcher->pilferPointers(monitor.getToken());
3084
3085 // Second finger down on window, the window should not receive touch down.
3086 const MotionEvent secondFingerDownEvent =
3087 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
3088 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
3089 AINPUT_SOURCE_TOUCHSCREEN)
3090 .displayId(ADISPLAY_ID_DEFAULT)
3091 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3092 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3093 .x(100)
3094 .y(200))
3095 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3096 .build();
3097 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3098 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
3099 InputEventInjectionSync::WAIT_FOR_RESULT))
3100 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3101
3102 window->assertNoEvents();
3103 monitor.consumeMotionPointerDown(1 /* pointerIndex */);
3104}
3105
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003106/**
3107 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3108 * the device default right away. In the test scenario, we check both the default value,
3109 * and the action of enabling / disabling.
3110 */
3111TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003112 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003113 sp<FakeWindowHandle> window =
3114 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003115 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003116
3117 // Set focused application.
3118 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003119 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003120
3121 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003122 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003123 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003124 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3125
3126 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003127 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003128 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003129 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3130
3131 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003132 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3133 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003134 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003135 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003136 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003137 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003138 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3139
3140 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003141 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003142 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003143 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3144
3145 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003146 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3147 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003148 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003149 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003150 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003151 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003152 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3153
3154 window->assertNoEvents();
3155}
3156
Gang Wange9087892020-01-07 12:17:14 -05003157TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003158 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003159 sp<FakeWindowHandle> window =
3160 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3161
3162 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003163 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003164
Arthur Hung72d8dc32020-03-28 00:48:39 +00003165 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003166 setFocusedWindow(window);
3167
Gang Wange9087892020-01-07 12:17:14 -05003168 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3169
3170 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3171 mDispatcher->notifyKey(&keyArgs);
3172
3173 InputEvent* event = window->consume();
3174 ASSERT_NE(event, nullptr);
3175
3176 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3177 ASSERT_NE(verified, nullptr);
3178 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3179
3180 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3181 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3182 ASSERT_EQ(keyArgs.source, verified->source);
3183 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3184
3185 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3186
3187 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003188 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003189 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003190 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3191 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3192 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3193 ASSERT_EQ(0, verifiedKey.repeatCount);
3194}
3195
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003196TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003197 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003198 sp<FakeWindowHandle> window =
3199 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3200
3201 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3202
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003203 ui::Transform transform;
3204 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3205
3206 gui::DisplayInfo displayInfo;
3207 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3208 displayInfo.transform = transform;
3209
3210 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003211
3212 NotifyMotionArgs motionArgs =
3213 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3214 ADISPLAY_ID_DEFAULT);
3215 mDispatcher->notifyMotion(&motionArgs);
3216
3217 InputEvent* event = window->consume();
3218 ASSERT_NE(event, nullptr);
3219
3220 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3221 ASSERT_NE(verified, nullptr);
3222 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3223
3224 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3225 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3226 EXPECT_EQ(motionArgs.source, verified->source);
3227 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3228
3229 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3230
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003231 const vec2 rawXY =
3232 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3233 motionArgs.pointerCoords[0].getXYValue());
3234 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3235 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003236 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003237 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003238 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003239 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3240 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3241}
3242
chaviw09c8d2d2020-08-24 15:48:26 -07003243/**
3244 * Ensure that separate calls to sign the same data are generating the same key.
3245 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3246 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3247 * tests.
3248 */
3249TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3250 KeyEvent event = getTestKeyEvent();
3251 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3252
3253 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3254 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3255 ASSERT_EQ(hmac1, hmac2);
3256}
3257
3258/**
3259 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3260 */
3261TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3262 KeyEvent event = getTestKeyEvent();
3263 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3264 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3265
3266 verifiedEvent.deviceId += 1;
3267 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3268
3269 verifiedEvent.source += 1;
3270 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3271
3272 verifiedEvent.eventTimeNanos += 1;
3273 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3274
3275 verifiedEvent.displayId += 1;
3276 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3277
3278 verifiedEvent.action += 1;
3279 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3280
3281 verifiedEvent.downTimeNanos += 1;
3282 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3283
3284 verifiedEvent.flags += 1;
3285 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3286
3287 verifiedEvent.keyCode += 1;
3288 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3289
3290 verifiedEvent.scanCode += 1;
3291 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3292
3293 verifiedEvent.metaState += 1;
3294 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3295
3296 verifiedEvent.repeatCount += 1;
3297 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3298}
3299
Vishnu Nair958da932020-08-21 17:12:37 -07003300TEST_F(InputDispatcherTest, SetFocusedWindow) {
3301 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3302 sp<FakeWindowHandle> windowTop =
3303 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3304 sp<FakeWindowHandle> windowSecond =
3305 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3306 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3307
3308 // Top window is also focusable but is not granted focus.
3309 windowTop->setFocusable(true);
3310 windowSecond->setFocusable(true);
3311 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3312 setFocusedWindow(windowSecond);
3313
3314 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003315 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3316 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003317
3318 // Focused window should receive event.
3319 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3320 windowTop->assertNoEvents();
3321}
3322
3323TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3324 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3325 sp<FakeWindowHandle> window =
3326 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3327 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3328
3329 window->setFocusable(true);
3330 // Release channel for window is no longer valid.
3331 window->releaseChannel();
3332 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3333 setFocusedWindow(window);
3334
3335 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003336 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3337 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003338
3339 // window channel is invalid, so it should not receive any input event.
3340 window->assertNoEvents();
3341}
3342
3343TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3344 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3345 sp<FakeWindowHandle> window =
3346 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3347 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3348
3349 // Window is not focusable.
3350 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3351 setFocusedWindow(window);
3352
3353 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003354 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3355 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003356
3357 // window is invalid, so it should not receive any input event.
3358 window->assertNoEvents();
3359}
3360
3361TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3362 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3363 sp<FakeWindowHandle> windowTop =
3364 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3365 sp<FakeWindowHandle> windowSecond =
3366 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3367 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3368
3369 windowTop->setFocusable(true);
3370 windowSecond->setFocusable(true);
3371 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3372 setFocusedWindow(windowTop);
3373 windowTop->consumeFocusEvent(true);
3374
3375 setFocusedWindow(windowSecond, windowTop);
3376 windowSecond->consumeFocusEvent(true);
3377 windowTop->consumeFocusEvent(false);
3378
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003379 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3380 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003381
3382 // Focused window should receive event.
3383 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3384}
3385
3386TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3387 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3388 sp<FakeWindowHandle> windowTop =
3389 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3390 sp<FakeWindowHandle> windowSecond =
3391 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3392 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3393
3394 windowTop->setFocusable(true);
3395 windowSecond->setFocusable(true);
3396 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3397 setFocusedWindow(windowSecond, windowTop);
3398
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003399 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3400 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003401
3402 // Event should be dropped.
3403 windowTop->assertNoEvents();
3404 windowSecond->assertNoEvents();
3405}
3406
3407TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3408 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3409 sp<FakeWindowHandle> window =
3410 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3411 sp<FakeWindowHandle> previousFocusedWindow =
3412 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3413 ADISPLAY_ID_DEFAULT);
3414 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3415
3416 window->setFocusable(true);
3417 previousFocusedWindow->setFocusable(true);
3418 window->setVisible(false);
3419 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3420 setFocusedWindow(previousFocusedWindow);
3421 previousFocusedWindow->consumeFocusEvent(true);
3422
3423 // Requesting focus on invisible window takes focus from currently focused window.
3424 setFocusedWindow(window);
3425 previousFocusedWindow->consumeFocusEvent(false);
3426
3427 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003428 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003429 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003430 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003431
3432 // Window does not get focus event or key down.
3433 window->assertNoEvents();
3434
3435 // Window becomes visible.
3436 window->setVisible(true);
3437 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3438
3439 // Window receives focus event.
3440 window->consumeFocusEvent(true);
3441 // Focused window receives key down.
3442 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3443}
3444
Vishnu Nair599f1412021-06-21 10:39:58 -07003445TEST_F(InputDispatcherTest, DisplayRemoved) {
3446 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3447 sp<FakeWindowHandle> window =
3448 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3449 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3450
3451 // window is granted focus.
3452 window->setFocusable(true);
3453 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3454 setFocusedWindow(window);
3455 window->consumeFocusEvent(true);
3456
3457 // When a display is removed window loses focus.
3458 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3459 window->consumeFocusEvent(false);
3460}
3461
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003462/**
3463 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3464 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3465 * of the 'slipperyEnterWindow'.
3466 *
3467 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3468 * a way so that the touched location is no longer covered by the top window.
3469 *
3470 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3471 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3472 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3473 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3474 * with ACTION_DOWN).
3475 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3476 * window moved itself away from the touched location and had Flag::SLIPPERY.
3477 *
3478 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3479 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3480 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3481 *
3482 * In this test, we ensure that the event received by the bottom window has
3483 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3484 */
3485TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3486 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3487 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3488
3489 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3490 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3491
3492 sp<FakeWindowHandle> slipperyExitWindow =
3493 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003494 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003495 // Make sure this one overlaps the bottom window
3496 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3497 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3498 // one. Windows with the same owner are not considered to be occluding each other.
3499 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3500
3501 sp<FakeWindowHandle> slipperyEnterWindow =
3502 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3503 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3504
3505 mDispatcher->setInputWindows(
3506 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3507
3508 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3509 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3510 ADISPLAY_ID_DEFAULT, {{50, 50}});
3511 mDispatcher->notifyMotion(&args);
3512 slipperyExitWindow->consumeMotionDown();
3513 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3514 mDispatcher->setInputWindows(
3515 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3516
3517 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3518 ADISPLAY_ID_DEFAULT, {{51, 51}});
3519 mDispatcher->notifyMotion(&args);
3520
3521 slipperyExitWindow->consumeMotionCancel();
3522
3523 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3524 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3525}
3526
Garfield Tan1c7bc862020-01-28 13:24:04 -08003527class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3528protected:
3529 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3530 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3531
Chris Yea209fde2020-07-22 13:54:51 -07003532 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003533 sp<FakeWindowHandle> mWindow;
3534
3535 virtual void SetUp() override {
3536 mFakePolicy = new FakeInputDispatcherPolicy();
3537 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003538 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003539 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3540 ASSERT_EQ(OK, mDispatcher->start());
3541
3542 setUpWindow();
3543 }
3544
3545 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003546 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003547 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3548
Vishnu Nair47074b82020-08-14 11:54:47 -07003549 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003550 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003551 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003552 mWindow->consumeFocusEvent(true);
3553 }
3554
Chris Ye2ad95392020-09-01 13:44:44 -07003555 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003556 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003557 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003558 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3559 mDispatcher->notifyKey(&keyArgs);
3560
3561 // Window should receive key down event.
3562 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3563 }
3564
3565 void expectKeyRepeatOnce(int32_t repeatCount) {
3566 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3567 InputEvent* repeatEvent = mWindow->consume();
3568 ASSERT_NE(nullptr, repeatEvent);
3569
3570 uint32_t eventType = repeatEvent->getType();
3571 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3572
3573 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3574 uint32_t eventAction = repeatKeyEvent->getAction();
3575 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3576 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3577 }
3578
Chris Ye2ad95392020-09-01 13:44:44 -07003579 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003580 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003581 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003582 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3583 mDispatcher->notifyKey(&keyArgs);
3584
3585 // Window should receive key down event.
3586 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3587 0 /*expectedFlags*/);
3588 }
3589};
3590
3591TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003592 sendAndConsumeKeyDown(1 /* deviceId */);
3593 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3594 expectKeyRepeatOnce(repeatCount);
3595 }
3596}
3597
3598TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3599 sendAndConsumeKeyDown(1 /* deviceId */);
3600 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3601 expectKeyRepeatOnce(repeatCount);
3602 }
3603 sendAndConsumeKeyDown(2 /* deviceId */);
3604 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003605 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3606 expectKeyRepeatOnce(repeatCount);
3607 }
3608}
3609
3610TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003611 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003612 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003613 sendAndConsumeKeyUp(1 /* deviceId */);
3614 mWindow->assertNoEvents();
3615}
3616
3617TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3618 sendAndConsumeKeyDown(1 /* deviceId */);
3619 expectKeyRepeatOnce(1 /*repeatCount*/);
3620 sendAndConsumeKeyDown(2 /* deviceId */);
3621 expectKeyRepeatOnce(1 /*repeatCount*/);
3622 // Stale key up from device 1.
3623 sendAndConsumeKeyUp(1 /* deviceId */);
3624 // Device 2 is still down, keep repeating
3625 expectKeyRepeatOnce(2 /*repeatCount*/);
3626 expectKeyRepeatOnce(3 /*repeatCount*/);
3627 // Device 2 key up
3628 sendAndConsumeKeyUp(2 /* deviceId */);
3629 mWindow->assertNoEvents();
3630}
3631
3632TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3633 sendAndConsumeKeyDown(1 /* deviceId */);
3634 expectKeyRepeatOnce(1 /*repeatCount*/);
3635 sendAndConsumeKeyDown(2 /* deviceId */);
3636 expectKeyRepeatOnce(1 /*repeatCount*/);
3637 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3638 sendAndConsumeKeyUp(2 /* deviceId */);
3639 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003640 mWindow->assertNoEvents();
3641}
3642
liushenxiang42232912021-05-21 20:24:09 +08003643TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3644 sendAndConsumeKeyDown(DEVICE_ID);
3645 expectKeyRepeatOnce(1 /*repeatCount*/);
3646 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3647 mDispatcher->notifyDeviceReset(&args);
3648 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3649 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3650 mWindow->assertNoEvents();
3651}
3652
Garfield Tan1c7bc862020-01-28 13:24:04 -08003653TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003654 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003655 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3656 InputEvent* repeatEvent = mWindow->consume();
3657 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3658 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3659 IdGenerator::getSource(repeatEvent->getId()));
3660 }
3661}
3662
3663TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003664 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003665
3666 std::unordered_set<int32_t> idSet;
3667 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3668 InputEvent* repeatEvent = mWindow->consume();
3669 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3670 int32_t id = repeatEvent->getId();
3671 EXPECT_EQ(idSet.end(), idSet.find(id));
3672 idSet.insert(id);
3673 }
3674}
3675
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003676/* Test InputDispatcher for MultiDisplay */
3677class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3678public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003679 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003680 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003681
Chris Yea209fde2020-07-22 13:54:51 -07003682 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003683 windowInPrimary =
3684 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003685
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003686 // Set focus window for primary display, but focused display would be second one.
3687 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003688 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003689 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003690 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003691 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003692
Chris Yea209fde2020-07-22 13:54:51 -07003693 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003694 windowInSecondary =
3695 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003696 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003697 // Set focus display to second one.
3698 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3699 // Set focus window for second display.
3700 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003701 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003702 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003703 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003704 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003705 }
3706
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003707 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003708 InputDispatcherTest::TearDown();
3709
Chris Yea209fde2020-07-22 13:54:51 -07003710 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003711 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003712 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003713 windowInSecondary.clear();
3714 }
3715
3716protected:
Chris Yea209fde2020-07-22 13:54:51 -07003717 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003718 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003719 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003720 sp<FakeWindowHandle> windowInSecondary;
3721};
3722
3723TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3724 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003725 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3726 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3727 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003728 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003729 windowInSecondary->assertNoEvents();
3730
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003731 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003732 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3733 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3734 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003735 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003736 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003737}
3738
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003739TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003740 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003741 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3742 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003743 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003744 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003745 windowInSecondary->assertNoEvents();
3746
3747 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003748 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003749 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003750 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003751 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003752
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003753 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003754 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003755
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003756 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003757 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3758 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003759
3760 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003761 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003762 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003763 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003764 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003765 windowInSecondary->assertNoEvents();
3766}
3767
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003768// Test per-display input monitors for motion event.
3769TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003770 FakeMonitorReceiver monitorInPrimary =
3771 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3772 FakeMonitorReceiver monitorInSecondary =
3773 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003774
3775 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003776 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3777 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3778 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003779 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003780 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003781 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003782 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003783
3784 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003785 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3786 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3787 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003788 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003789 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003790 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003791 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003792
3793 // Test inject a non-pointer motion event.
3794 // If specific a display, it will dispatch to the focused window of particular display,
3795 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003796 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3797 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3798 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003799 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003800 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003801 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003802 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003803}
3804
3805// Test per-display input monitors for key event.
3806TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003807 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003808 FakeMonitorReceiver monitorInPrimary =
3809 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3810 FakeMonitorReceiver monitorInSecondary =
3811 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003812
3813 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003814 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3815 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003816 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003817 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003818 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003819 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003820}
3821
Vishnu Nair958da932020-08-21 17:12:37 -07003822TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3823 sp<FakeWindowHandle> secondWindowInPrimary =
3824 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3825 secondWindowInPrimary->setFocusable(true);
3826 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3827 setFocusedWindow(secondWindowInPrimary);
3828 windowInPrimary->consumeFocusEvent(false);
3829 secondWindowInPrimary->consumeFocusEvent(true);
3830
3831 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003832 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3833 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003834 windowInPrimary->assertNoEvents();
3835 windowInSecondary->assertNoEvents();
3836 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3837}
3838
Arthur Hungdfd528e2021-12-08 13:23:04 +00003839TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3840 FakeMonitorReceiver monitorInPrimary =
3841 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3842 FakeMonitorReceiver monitorInSecondary =
3843 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3844
3845 // Test touch down on primary display.
3846 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3847 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3848 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3849 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3850 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3851
3852 // Test touch down on second display.
3853 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3854 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3855 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3856 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3857 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3858
3859 // Trigger cancel touch.
3860 mDispatcher->cancelCurrentTouch();
3861 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3862 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3863 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3864 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3865
3866 // Test inject a move motion event, no window/monitor should receive the event.
3867 ASSERT_EQ(InputEventInjectionResult::FAILED,
3868 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3869 ADISPLAY_ID_DEFAULT, {110, 200}))
3870 << "Inject motion event should return InputEventInjectionResult::FAILED";
3871 windowInPrimary->assertNoEvents();
3872 monitorInPrimary.assertNoEvents();
3873
3874 ASSERT_EQ(InputEventInjectionResult::FAILED,
3875 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3876 SECOND_DISPLAY_ID, {110, 200}))
3877 << "Inject motion event should return InputEventInjectionResult::FAILED";
3878 windowInSecondary->assertNoEvents();
3879 monitorInSecondary.assertNoEvents();
3880}
3881
Jackal Guof9696682018-10-05 12:23:23 +08003882class InputFilterTest : public InputDispatcherTest {
3883protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003884 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3885 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003886 NotifyMotionArgs motionArgs;
3887
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003888 motionArgs =
3889 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003890 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003891 motionArgs =
3892 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003893 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003894 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003895 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003896 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3897 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003898 } else {
3899 mFakePolicy->assertFilterInputEventWasNotCalled();
3900 }
3901 }
3902
3903 void testNotifyKey(bool expectToBeFiltered) {
3904 NotifyKeyArgs keyArgs;
3905
3906 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3907 mDispatcher->notifyKey(&keyArgs);
3908 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3909 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003910 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003911
3912 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003913 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003914 } else {
3915 mFakePolicy->assertFilterInputEventWasNotCalled();
3916 }
3917 }
3918};
3919
3920// Test InputFilter for MotionEvent
3921TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3922 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3923 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3924 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3925
3926 // Enable InputFilter
3927 mDispatcher->setInputFilterEnabled(true);
3928 // Test touch on both primary and second display, and check if both events are filtered.
3929 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3930 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3931
3932 // Disable InputFilter
3933 mDispatcher->setInputFilterEnabled(false);
3934 // Test touch on both primary and second display, and check if both events aren't filtered.
3935 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3936 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3937}
3938
3939// Test InputFilter for KeyEvent
3940TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3941 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3942 testNotifyKey(/*expectToBeFiltered*/ false);
3943
3944 // Enable InputFilter
3945 mDispatcher->setInputFilterEnabled(true);
3946 // Send a key event, and check if it is filtered.
3947 testNotifyKey(/*expectToBeFiltered*/ true);
3948
3949 // Disable InputFilter
3950 mDispatcher->setInputFilterEnabled(false);
3951 // Send a key event, and check if it isn't filtered.
3952 testNotifyKey(/*expectToBeFiltered*/ false);
3953}
3954
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003955// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3956// logical display coordinate space.
3957TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3958 ui::Transform firstDisplayTransform;
3959 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3960 ui::Transform secondDisplayTransform;
3961 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3962
3963 std::vector<gui::DisplayInfo> displayInfos(2);
3964 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3965 displayInfos[0].transform = firstDisplayTransform;
3966 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3967 displayInfos[1].transform = secondDisplayTransform;
3968
3969 mDispatcher->onWindowInfosChanged({}, displayInfos);
3970
3971 // Enable InputFilter
3972 mDispatcher->setInputFilterEnabled(true);
3973
3974 // Ensure the correct transforms are used for the displays.
3975 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3976 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3977}
3978
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003979class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3980protected:
3981 virtual void SetUp() override {
3982 InputDispatcherTest::SetUp();
3983
3984 /**
3985 * We don't need to enable input filter to test the injected event policy, but we enabled it
3986 * here to make the tests more realistic, since this policy only matters when inputfilter is
3987 * on.
3988 */
3989 mDispatcher->setInputFilterEnabled(true);
3990
3991 std::shared_ptr<InputApplicationHandle> application =
3992 std::make_shared<FakeApplicationHandle>();
3993 mWindow =
3994 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3995
3996 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3997 mWindow->setFocusable(true);
3998 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3999 setFocusedWindow(mWindow);
4000 mWindow->consumeFocusEvent(true);
4001 }
4002
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004003 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4004 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004005 KeyEvent event;
4006
4007 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4008 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4009 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4010 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4011 const int32_t additionalPolicyFlags =
4012 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4013 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4014 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
4015 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4016 policyFlags | additionalPolicyFlags));
4017
4018 InputEvent* received = mWindow->consume();
4019 ASSERT_NE(nullptr, received);
4020 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004021 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4022 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4023 ASSERT_EQ(flags, keyEvent.getFlags());
4024 }
4025
4026 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4027 int32_t flags) {
4028 MotionEvent event;
4029 PointerProperties pointerProperties[1];
4030 PointerCoords pointerCoords[1];
4031 pointerProperties[0].clear();
4032 pointerProperties[0].id = 0;
4033 pointerCoords[0].clear();
4034 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4035 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4036
4037 ui::Transform identityTransform;
4038 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4039 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4040 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4041 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4042 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004043 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004044 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004045 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4046
4047 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4048 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4049 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
4050 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4051 policyFlags | additionalPolicyFlags));
4052
4053 InputEvent* received = mWindow->consume();
4054 ASSERT_NE(nullptr, received);
4055 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4056 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4057 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4058 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004059 }
4060
4061private:
4062 sp<FakeWindowHandle> mWindow;
4063};
4064
4065TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004066 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4067 // filter. Without it, the event will no different from a regularly injected event, and the
4068 // injected device id will be overwritten.
4069 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4070 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004071}
4072
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004073TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004074 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004075 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4076 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4077}
4078
4079TEST_F(InputFilterInjectionPolicyTest,
4080 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4081 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4082 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4083 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004084}
4085
4086TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4087 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004088 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004089}
4090
chaviwfd6d3512019-03-25 13:23:49 -07004091class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004092 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004093 InputDispatcherTest::SetUp();
4094
Chris Yea209fde2020-07-22 13:54:51 -07004095 std::shared_ptr<FakeApplicationHandle> application =
4096 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004097 mUnfocusedWindow =
4098 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004099 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4100 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4101 // window.
chaviw3277faf2021-05-19 16:45:23 -05004102 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07004103
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004104 mFocusedWindow =
4105 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4106 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004107 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07004108
4109 // Set focused application.
4110 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004111 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004112
4113 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004114 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004115 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004116 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004117 }
4118
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004119 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004120 InputDispatcherTest::TearDown();
4121
4122 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004123 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004124 }
4125
4126protected:
4127 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004128 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004129 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004130};
4131
4132// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4133// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4134// the onPointerDownOutsideFocus callback.
4135TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004136 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004137 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4138 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004139 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004140 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004141
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004142 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004143 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4144}
4145
4146// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4147// DOWN on the window that doesn't have focus. Ensure no window received the
4148// onPointerDownOutsideFocus callback.
4149TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004150 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004151 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004152 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004153 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004154
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004155 ASSERT_TRUE(mDispatcher->waitForIdle());
4156 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004157}
4158
4159// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4160// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4161TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004162 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4163 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004164 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004165 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004166
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004167 ASSERT_TRUE(mDispatcher->waitForIdle());
4168 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004169}
4170
4171// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4172// DOWN on the window that already has focus. Ensure no window received the
4173// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004174TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004175 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004176 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004177 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004178 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004179 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004180
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004181 ASSERT_TRUE(mDispatcher->waitForIdle());
4182 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004183}
4184
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004185// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4186// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4187TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4188 const MotionEvent event =
4189 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4190 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4191 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4192 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4193 .build();
4194 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4195 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4196 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4197
4198 ASSERT_TRUE(mDispatcher->waitForIdle());
4199 mFakePolicy->assertOnPointerDownWasNotCalled();
4200 // Ensure that the unfocused window did not receive any FOCUS events.
4201 mUnfocusedWindow->assertNoEvents();
4202}
4203
chaviwaf87b3e2019-10-01 16:59:28 -07004204// These tests ensures we can send touch events to a single client when there are multiple input
4205// windows that point to the same client token.
4206class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4207 virtual void SetUp() override {
4208 InputDispatcherTest::SetUp();
4209
Chris Yea209fde2020-07-22 13:54:51 -07004210 std::shared_ptr<FakeApplicationHandle> application =
4211 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004212 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4213 ADISPLAY_ID_DEFAULT);
4214 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
4215 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05004216 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004217 mWindow1->setFrame(Rect(0, 0, 100, 100));
4218
4219 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4220 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05004221 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004222 mWindow2->setFrame(Rect(100, 100, 200, 200));
4223
Arthur Hung72d8dc32020-03-28 00:48:39 +00004224 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004225 }
4226
4227protected:
4228 sp<FakeWindowHandle> mWindow1;
4229 sp<FakeWindowHandle> mWindow2;
4230
4231 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004232 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004233 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4234 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004235 }
4236
4237 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4238 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004239 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004240 InputEvent* event = window->consume();
4241
4242 ASSERT_NE(nullptr, event) << name.c_str()
4243 << ": consumer should have returned non-NULL event.";
4244
4245 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4246 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4247 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4248
4249 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004250 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004251
4252 for (size_t i = 0; i < points.size(); i++) {
4253 float expectedX = points[i].x;
4254 float expectedY = points[i].y;
4255
4256 EXPECT_EQ(expectedX, motionEvent.getX(i))
4257 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4258 << ", got " << motionEvent.getX(i);
4259 EXPECT_EQ(expectedY, motionEvent.getY(i))
4260 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4261 << ", got " << motionEvent.getY(i);
4262 }
4263 }
chaviw9eaa22c2020-07-01 16:21:27 -07004264
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004265 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004266 std::vector<PointF> expectedPoints) {
4267 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4268 ADISPLAY_ID_DEFAULT, touchedPoints);
4269 mDispatcher->notifyMotion(&motionArgs);
4270
4271 // Always consume from window1 since it's the window that has the InputReceiver
4272 consumeMotionEvent(mWindow1, action, expectedPoints);
4273 }
chaviwaf87b3e2019-10-01 16:59:28 -07004274};
4275
4276TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4277 // Touch Window 1
4278 PointF touchedPoint = {10, 10};
4279 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004280 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004281
4282 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004283 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004284
4285 // Touch Window 2
4286 touchedPoint = {150, 150};
4287 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004288 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004289}
4290
chaviw9eaa22c2020-07-01 16:21:27 -07004291TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4292 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004293 mWindow2->setWindowScale(0.5f, 0.5f);
4294
4295 // Touch Window 1
4296 PointF touchedPoint = {10, 10};
4297 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004298 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004299 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004300 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004301
4302 // Touch Window 2
4303 touchedPoint = {150, 150};
4304 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004305 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4306 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004307
chaviw9eaa22c2020-07-01 16:21:27 -07004308 // Update the transform so rotation is set
4309 mWindow2->setWindowTransform(0, -1, 1, 0);
4310 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4311 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004312}
4313
chaviw9eaa22c2020-07-01 16:21:27 -07004314TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004315 mWindow2->setWindowScale(0.5f, 0.5f);
4316
4317 // Touch Window 1
4318 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4319 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004320 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004321
4322 // Touch Window 2
4323 int32_t actionPointerDown =
4324 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004325 touchedPoints.push_back(PointF{150, 150});
4326 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4327 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004328
chaviw9eaa22c2020-07-01 16:21:27 -07004329 // Release Window 2
4330 int32_t actionPointerUp =
4331 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4332 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4333 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004334
chaviw9eaa22c2020-07-01 16:21:27 -07004335 // Update the transform so rotation is set for Window 2
4336 mWindow2->setWindowTransform(0, -1, 1, 0);
4337 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4338 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004339}
4340
chaviw9eaa22c2020-07-01 16:21:27 -07004341TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004342 mWindow2->setWindowScale(0.5f, 0.5f);
4343
4344 // Touch Window 1
4345 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4346 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004347 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004348
4349 // Touch Window 2
4350 int32_t actionPointerDown =
4351 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004352 touchedPoints.push_back(PointF{150, 150});
4353 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004354
chaviw9eaa22c2020-07-01 16:21:27 -07004355 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004356
4357 // Move both windows
4358 touchedPoints = {{20, 20}, {175, 175}};
4359 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4360 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4361
chaviw9eaa22c2020-07-01 16:21:27 -07004362 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004363
chaviw9eaa22c2020-07-01 16:21:27 -07004364 // Release Window 2
4365 int32_t actionPointerUp =
4366 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4367 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4368 expectedPoints.pop_back();
4369
4370 // Touch Window 2
4371 mWindow2->setWindowTransform(0, -1, 1, 0);
4372 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4373 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4374
4375 // Move both windows
4376 touchedPoints = {{20, 20}, {175, 175}};
4377 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4378 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4379
4380 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004381}
4382
4383TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4384 mWindow1->setWindowScale(0.5f, 0.5f);
4385
4386 // Touch Window 1
4387 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4388 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004389 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004390
4391 // Touch Window 2
4392 int32_t actionPointerDown =
4393 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004394 touchedPoints.push_back(PointF{150, 150});
4395 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004396
chaviw9eaa22c2020-07-01 16:21:27 -07004397 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004398
4399 // Move both windows
4400 touchedPoints = {{20, 20}, {175, 175}};
4401 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4402 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4403
chaviw9eaa22c2020-07-01 16:21:27 -07004404 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004405}
4406
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004407class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4408 virtual void SetUp() override {
4409 InputDispatcherTest::SetUp();
4410
Chris Yea209fde2020-07-22 13:54:51 -07004411 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004412 mApplication->setDispatchingTimeout(20ms);
4413 mWindow =
4414 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4415 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004416 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004417 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004418 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4419 // window.
chaviw3277faf2021-05-19 16:45:23 -05004420 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004421
4422 // Set focused application.
4423 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4424
4425 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004426 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004427 mWindow->consumeFocusEvent(true);
4428 }
4429
4430 virtual void TearDown() override {
4431 InputDispatcherTest::TearDown();
4432 mWindow.clear();
4433 }
4434
4435protected:
Chris Yea209fde2020-07-22 13:54:51 -07004436 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004437 sp<FakeWindowHandle> mWindow;
4438 static constexpr PointF WINDOW_LOCATION = {20, 20};
4439
4440 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004441 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004442 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4443 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004444 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004445 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4446 WINDOW_LOCATION));
4447 }
4448};
4449
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004450// Send a tap and respond, which should not cause an ANR.
4451TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4452 tapOnWindow();
4453 mWindow->consumeMotionDown();
4454 mWindow->consumeMotionUp();
4455 ASSERT_TRUE(mDispatcher->waitForIdle());
4456 mFakePolicy->assertNotifyAnrWasNotCalled();
4457}
4458
4459// Send a regular key and respond, which should not cause an ANR.
4460TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004461 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004462 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4463 ASSERT_TRUE(mDispatcher->waitForIdle());
4464 mFakePolicy->assertNotifyAnrWasNotCalled();
4465}
4466
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004467TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4468 mWindow->setFocusable(false);
4469 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4470 mWindow->consumeFocusEvent(false);
4471
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004472 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004473 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004474 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4475 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004476 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004477 // Key will not go to window because we have no focused window.
4478 // The 'no focused window' ANR timer should start instead.
4479
4480 // Now, the focused application goes away.
4481 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4482 // The key should get dropped and there should be no ANR.
4483
4484 ASSERT_TRUE(mDispatcher->waitForIdle());
4485 mFakePolicy->assertNotifyAnrWasNotCalled();
4486}
4487
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004488// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004489// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4490// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004491TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004492 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004493 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4494 WINDOW_LOCATION));
4495
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004496 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4497 ASSERT_TRUE(sequenceNum);
4498 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004499 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004500
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004501 mWindow->finishEvent(*sequenceNum);
4502 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4503 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004504 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004505 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004506}
4507
4508// Send a key to the app and have the app not respond right away.
4509TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4510 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004511 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004512 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4513 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004514 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004515 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004516 ASSERT_TRUE(mDispatcher->waitForIdle());
4517}
4518
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004519// We have a focused application, but no focused window
4520TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004521 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004522 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4523 mWindow->consumeFocusEvent(false);
4524
4525 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004526 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004527 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4528 WINDOW_LOCATION));
4529 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4530 mDispatcher->waitForIdle();
4531 mFakePolicy->assertNotifyAnrWasNotCalled();
4532
4533 // Once a focused event arrives, we get an ANR for this application
4534 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4535 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004536 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004537 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004538 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004539 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004540 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004541 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004542 ASSERT_TRUE(mDispatcher->waitForIdle());
4543}
4544
4545// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004546// Make sure that we don't notify policy twice about the same ANR.
4547TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004548 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004549 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4550 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004551
4552 // Once a focused event arrives, we get an ANR for this application
4553 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4554 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004555 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004556 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004557 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004558 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004559 const std::chrono::duration appTimeout =
4560 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004561 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004562
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004563 std::this_thread::sleep_for(appTimeout);
4564 // ANR should not be raised again. It is up to policy to do that if it desires.
4565 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004566
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004567 // If we now get a focused window, the ANR should stop, but the policy handles that via
4568 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004569 ASSERT_TRUE(mDispatcher->waitForIdle());
4570}
4571
4572// We have a focused application, but no focused window
4573TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004574 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004575 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4576 mWindow->consumeFocusEvent(false);
4577
4578 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004579 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004580 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004581 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4582 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004583
4584 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004585 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004586
4587 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004588 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004589 ASSERT_TRUE(mDispatcher->waitForIdle());
4590 mWindow->assertNoEvents();
4591}
4592
4593/**
4594 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4595 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4596 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4597 * the ANR mechanism should still work.
4598 *
4599 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4600 * DOWN event, while not responding on the second one.
4601 */
4602TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4603 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4604 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4605 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4606 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4607 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004608 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004609
4610 // Now send ACTION_UP, with identical timestamp
4611 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4612 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4613 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4614 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004615 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004616
4617 // We have now sent down and up. Let's consume first event and then ANR on the second.
4618 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4619 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004620 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004621}
4622
4623// If an app is not responding to a key event, gesture monitors should continue to receive
4624// new motion events
4625TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
4626 FakeMonitorReceiver monitor =
4627 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4628 true /*isGestureMonitor*/);
4629
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004630 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4631 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004632 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004633 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004634
4635 // Stuck on the ACTION_UP
4636 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004637 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004638
4639 // New tap will go to the gesture monitor, but not to the window
4640 tapOnWindow();
4641 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4642 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4643
4644 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4645 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004646 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004647 mWindow->assertNoEvents();
4648 monitor.assertNoEvents();
4649}
4650
4651// If an app is not responding to a motion event, gesture monitors should continue to receive
4652// new motion events
4653TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
4654 FakeMonitorReceiver monitor =
4655 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4656 true /*isGestureMonitor*/);
4657
4658 tapOnWindow();
4659 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4660 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4661
4662 mWindow->consumeMotionDown();
4663 // Stuck on the ACTION_UP
4664 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004665 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004666
4667 // New tap will go to the gesture monitor, but not to the window
4668 tapOnWindow();
4669 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4670 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4671
4672 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4673 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004674 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004675 mWindow->assertNoEvents();
4676 monitor.assertNoEvents();
4677}
4678
4679// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4680// process events, you don't get an anr. When the window later becomes unresponsive again, you
4681// get an ANR again.
4682// 1. tap -> block on ACTION_UP -> receive ANR
4683// 2. consume all pending events (= queue becomes healthy again)
4684// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4685TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4686 tapOnWindow();
4687
4688 mWindow->consumeMotionDown();
4689 // Block on ACTION_UP
4690 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004691 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004692 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4693 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004694 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004695 mWindow->assertNoEvents();
4696
4697 tapOnWindow();
4698 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004699 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004700 mWindow->consumeMotionUp();
4701
4702 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004703 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004704 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004705 mWindow->assertNoEvents();
4706}
4707
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004708// If a connection remains unresponsive for a while, make sure policy is only notified once about
4709// it.
4710TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004711 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004712 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4713 WINDOW_LOCATION));
4714
4715 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004716 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004717 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004718 // 'notifyConnectionUnresponsive' should only be called once per connection
4719 mFakePolicy->assertNotifyAnrWasNotCalled();
4720 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004721 mWindow->consumeMotionDown();
4722 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4723 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4724 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004725 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004726 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004727 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004728}
4729
4730/**
4731 * If a window is processing a motion event, and then a key event comes in, the key event should
4732 * not to to the focused window until the motion is processed.
4733 *
4734 * Warning!!!
4735 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4736 * and the injection timeout that we specify when injecting the key.
4737 * We must have the injection timeout (10ms) be smaller than
4738 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4739 *
4740 * If that value changes, this test should also change.
4741 */
4742TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4743 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4744 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4745
4746 tapOnWindow();
4747 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4748 ASSERT_TRUE(downSequenceNum);
4749 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4750 ASSERT_TRUE(upSequenceNum);
4751 // Don't finish the events yet, and send a key
4752 // Injection will "succeed" because we will eventually give up and send the key to the focused
4753 // window even if motions are still being processed. But because the injection timeout is short,
4754 // we will receive INJECTION_TIMED_OUT as the result.
4755
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004756 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004757 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004758 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4759 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004760 // Key will not be sent to the window, yet, because the window is still processing events
4761 // and the key remains pending, waiting for the touch events to be processed
4762 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4763 ASSERT_FALSE(keySequenceNum);
4764
4765 std::this_thread::sleep_for(500ms);
4766 // if we wait long enough though, dispatcher will give up, and still send the key
4767 // to the focused window, even though we have not yet finished the motion event
4768 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4769 mWindow->finishEvent(*downSequenceNum);
4770 mWindow->finishEvent(*upSequenceNum);
4771}
4772
4773/**
4774 * If a window is processing a motion event, and then a key event comes in, the key event should
4775 * not go to the focused window until the motion is processed.
4776 * If then a new motion comes in, then the pending key event should be going to the currently
4777 * focused window right away.
4778 */
4779TEST_F(InputDispatcherSingleWindowAnr,
4780 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4781 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4782 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4783
4784 tapOnWindow();
4785 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4786 ASSERT_TRUE(downSequenceNum);
4787 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4788 ASSERT_TRUE(upSequenceNum);
4789 // Don't finish the events yet, and send a key
4790 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004791 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004792 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004793 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004794 // At this point, key is still pending, and should not be sent to the application yet.
4795 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4796 ASSERT_FALSE(keySequenceNum);
4797
4798 // Now tap down again. It should cause the pending key to go to the focused window right away.
4799 tapOnWindow();
4800 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4801 // the other events yet. We can finish events in any order.
4802 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4803 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4804 mWindow->consumeMotionDown();
4805 mWindow->consumeMotionUp();
4806 mWindow->assertNoEvents();
4807}
4808
4809class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4810 virtual void SetUp() override {
4811 InputDispatcherTest::SetUp();
4812
Chris Yea209fde2020-07-22 13:54:51 -07004813 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004814 mApplication->setDispatchingTimeout(10ms);
4815 mUnfocusedWindow =
4816 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4817 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4818 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4819 // window.
4820 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004821 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4822 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4823 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004824
4825 mFocusedWindow =
4826 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004827 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004828 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004829 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004830
4831 // Set focused application.
4832 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004833 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004834
4835 // Expect one focus window exist in display.
4836 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004837 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004838 mFocusedWindow->consumeFocusEvent(true);
4839 }
4840
4841 virtual void TearDown() override {
4842 InputDispatcherTest::TearDown();
4843
4844 mUnfocusedWindow.clear();
4845 mFocusedWindow.clear();
4846 }
4847
4848protected:
Chris Yea209fde2020-07-22 13:54:51 -07004849 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004850 sp<FakeWindowHandle> mUnfocusedWindow;
4851 sp<FakeWindowHandle> mFocusedWindow;
4852 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4853 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4854 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4855
4856 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4857
4858 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4859
4860private:
4861 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004862 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004863 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4864 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004865 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004866 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4867 location));
4868 }
4869};
4870
4871// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4872// should be ANR'd first.
4873TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004874 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004875 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4876 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004877 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004878 mFocusedWindow->consumeMotionDown();
4879 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4880 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4881 // We consumed all events, so no ANR
4882 ASSERT_TRUE(mDispatcher->waitForIdle());
4883 mFakePolicy->assertNotifyAnrWasNotCalled();
4884
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004885 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004886 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4887 FOCUSED_WINDOW_LOCATION));
4888 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4889 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004890
4891 const std::chrono::duration timeout =
4892 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004893 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004894 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4895 // sequence to make it consistent
4896 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004897 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004898 mFocusedWindow->consumeMotionDown();
4899 // This cancel is generated because the connection was unresponsive
4900 mFocusedWindow->consumeMotionCancel();
4901 mFocusedWindow->assertNoEvents();
4902 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004903 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004904 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004905 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004906}
4907
4908// If we have 2 windows with identical timeouts that are both unresponsive,
4909// it doesn't matter which order they should have ANR.
4910// But we should receive ANR for both.
4911TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4912 // Set the timeout for unfocused window to match the focused window
4913 mUnfocusedWindow->setDispatchingTimeout(10ms);
4914 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4915
4916 tapOnFocusedWindow();
4917 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004918 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4919 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004920
4921 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004922 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4923 mFocusedWindow->getToken() == anrConnectionToken2);
4924 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4925 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004926
4927 ASSERT_TRUE(mDispatcher->waitForIdle());
4928 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004929
4930 mFocusedWindow->consumeMotionDown();
4931 mFocusedWindow->consumeMotionUp();
4932 mUnfocusedWindow->consumeMotionOutside();
4933
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004934 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4935 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004936
4937 // Both applications should be marked as responsive, in any order
4938 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4939 mFocusedWindow->getToken() == responsiveToken2);
4940 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4941 mUnfocusedWindow->getToken() == responsiveToken2);
4942 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004943}
4944
4945// If a window is already not responding, the second tap on the same window should be ignored.
4946// We should also log an error to account for the dropped event (not tested here).
4947// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4948TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4949 tapOnFocusedWindow();
4950 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4951 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4952 // Receive the events, but don't respond
4953 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4954 ASSERT_TRUE(downEventSequenceNum);
4955 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4956 ASSERT_TRUE(upEventSequenceNum);
4957 const std::chrono::duration timeout =
4958 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004959 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004960
4961 // Tap once again
4962 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004963 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004964 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4965 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004966 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004967 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4968 FOCUSED_WINDOW_LOCATION));
4969 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4970 // valid touch target
4971 mUnfocusedWindow->assertNoEvents();
4972
4973 // Consume the first tap
4974 mFocusedWindow->finishEvent(*downEventSequenceNum);
4975 mFocusedWindow->finishEvent(*upEventSequenceNum);
4976 ASSERT_TRUE(mDispatcher->waitForIdle());
4977 // The second tap did not go to the focused window
4978 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004979 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004980 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004981 mFakePolicy->assertNotifyAnrWasNotCalled();
4982}
4983
4984// If you tap outside of all windows, there will not be ANR
4985TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004986 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004987 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4988 LOCATION_OUTSIDE_ALL_WINDOWS));
4989 ASSERT_TRUE(mDispatcher->waitForIdle());
4990 mFakePolicy->assertNotifyAnrWasNotCalled();
4991}
4992
4993// Since the focused window is paused, tapping on it should not produce any events
4994TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4995 mFocusedWindow->setPaused(true);
4996 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4997
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004998 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004999 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5000 FOCUSED_WINDOW_LOCATION));
5001
5002 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5003 ASSERT_TRUE(mDispatcher->waitForIdle());
5004 // Should not ANR because the window is paused, and touches shouldn't go to it
5005 mFakePolicy->assertNotifyAnrWasNotCalled();
5006
5007 mFocusedWindow->assertNoEvents();
5008 mUnfocusedWindow->assertNoEvents();
5009}
5010
5011/**
5012 * If a window is processing a motion event, and then a key event comes in, the key event should
5013 * not to to the focused window until the motion is processed.
5014 * If a different window becomes focused at this time, the key should go to that window instead.
5015 *
5016 * Warning!!!
5017 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5018 * and the injection timeout that we specify when injecting the key.
5019 * We must have the injection timeout (10ms) be smaller than
5020 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5021 *
5022 * If that value changes, this test should also change.
5023 */
5024TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5025 // Set a long ANR timeout to prevent it from triggering
5026 mFocusedWindow->setDispatchingTimeout(2s);
5027 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5028
5029 tapOnUnfocusedWindow();
5030 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5031 ASSERT_TRUE(downSequenceNum);
5032 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5033 ASSERT_TRUE(upSequenceNum);
5034 // Don't finish the events yet, and send a key
5035 // Injection will succeed because we will eventually give up and send the key to the focused
5036 // window even if motions are still being processed.
5037
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005038 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005039 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005040 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5041 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005042 // Key will not be sent to the window, yet, because the window is still processing events
5043 // and the key remains pending, waiting for the touch events to be processed
5044 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5045 ASSERT_FALSE(keySequenceNum);
5046
5047 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005048 mFocusedWindow->setFocusable(false);
5049 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005050 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005051 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005052
5053 // Focus events should precede the key events
5054 mUnfocusedWindow->consumeFocusEvent(true);
5055 mFocusedWindow->consumeFocusEvent(false);
5056
5057 // Finish the tap events, which should unblock dispatcher
5058 mUnfocusedWindow->finishEvent(*downSequenceNum);
5059 mUnfocusedWindow->finishEvent(*upSequenceNum);
5060
5061 // Now that all queues are cleared and no backlog in the connections, the key event
5062 // can finally go to the newly focused "mUnfocusedWindow".
5063 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5064 mFocusedWindow->assertNoEvents();
5065 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005066 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005067}
5068
5069// When the touch stream is split across 2 windows, and one of them does not respond,
5070// then ANR should be raised and the touch should be canceled for the unresponsive window.
5071// The other window should not be affected by that.
5072TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5073 // Touch Window 1
5074 NotifyMotionArgs motionArgs =
5075 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5076 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5077 mDispatcher->notifyMotion(&motionArgs);
5078 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5079 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5080
5081 // Touch Window 2
5082 int32_t actionPointerDown =
5083 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
5084
5085 motionArgs =
5086 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5087 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
5088 mDispatcher->notifyMotion(&motionArgs);
5089
5090 const std::chrono::duration timeout =
5091 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005092 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005093
5094 mUnfocusedWindow->consumeMotionDown();
5095 mFocusedWindow->consumeMotionDown();
5096 // Focused window may or may not receive ACTION_MOVE
5097 // But it should definitely receive ACTION_CANCEL due to the ANR
5098 InputEvent* event;
5099 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5100 ASSERT_TRUE(moveOrCancelSequenceNum);
5101 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5102 ASSERT_NE(nullptr, event);
5103 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5104 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5105 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5106 mFocusedWindow->consumeMotionCancel();
5107 } else {
5108 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5109 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005110 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005111 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005112
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005113 mUnfocusedWindow->assertNoEvents();
5114 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005115 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005116}
5117
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005118/**
5119 * If we have no focused window, and a key comes in, we start the ANR timer.
5120 * The focused application should add a focused window before the timer runs out to prevent ANR.
5121 *
5122 * If the user touches another application during this time, the key should be dropped.
5123 * Next, if a new focused window comes in, without toggling the focused application,
5124 * then no ANR should occur.
5125 *
5126 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5127 * but in some cases the policy may not update the focused application.
5128 */
5129TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5130 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5131 std::make_shared<FakeApplicationHandle>();
5132 focusedApplication->setDispatchingTimeout(60ms);
5133 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5134 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5135 mFocusedWindow->setFocusable(false);
5136
5137 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5138 mFocusedWindow->consumeFocusEvent(false);
5139
5140 // Send a key. The ANR timer should start because there is no focused window.
5141 // 'focusedApplication' will get blamed if this timer completes.
5142 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005143 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005144 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005145 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5146 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005147 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005148
5149 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5150 // then the injected touches won't cause the focused event to get dropped.
5151 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5152 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5153 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5154 // For this test, it means that the key would get delivered to the window once it becomes
5155 // focused.
5156 std::this_thread::sleep_for(10ms);
5157
5158 // Touch unfocused window. This should force the pending key to get dropped.
5159 NotifyMotionArgs motionArgs =
5160 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5161 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5162 mDispatcher->notifyMotion(&motionArgs);
5163
5164 // We do not consume the motion right away, because that would require dispatcher to first
5165 // process (== drop) the key event, and by that time, ANR will be raised.
5166 // Set the focused window first.
5167 mFocusedWindow->setFocusable(true);
5168 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5169 setFocusedWindow(mFocusedWindow);
5170 mFocusedWindow->consumeFocusEvent(true);
5171 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5172 // to another application. This could be a bug / behaviour in the policy.
5173
5174 mUnfocusedWindow->consumeMotionDown();
5175
5176 ASSERT_TRUE(mDispatcher->waitForIdle());
5177 // Should not ANR because we actually have a focused window. It was just added too slowly.
5178 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5179}
5180
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005181// These tests ensure we cannot send touch events to a window that's positioned behind a window
5182// that has feature NO_INPUT_CHANNEL.
5183// Layout:
5184// Top (closest to user)
5185// mNoInputWindow (above all windows)
5186// mBottomWindow
5187// Bottom (furthest from user)
5188class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5189 virtual void SetUp() override {
5190 InputDispatcherTest::SetUp();
5191
5192 mApplication = std::make_shared<FakeApplicationHandle>();
5193 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5194 "Window without input channel", ADISPLAY_ID_DEFAULT,
5195 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5196
chaviw3277faf2021-05-19 16:45:23 -05005197 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005198 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5199 // It's perfectly valid for this window to not have an associated input channel
5200
5201 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5202 ADISPLAY_ID_DEFAULT);
5203 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5204
5205 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5206 }
5207
5208protected:
5209 std::shared_ptr<FakeApplicationHandle> mApplication;
5210 sp<FakeWindowHandle> mNoInputWindow;
5211 sp<FakeWindowHandle> mBottomWindow;
5212};
5213
5214TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5215 PointF touchedPoint = {10, 10};
5216
5217 NotifyMotionArgs motionArgs =
5218 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5219 ADISPLAY_ID_DEFAULT, {touchedPoint});
5220 mDispatcher->notifyMotion(&motionArgs);
5221
5222 mNoInputWindow->assertNoEvents();
5223 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5224 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5225 // and therefore should prevent mBottomWindow from receiving touches
5226 mBottomWindow->assertNoEvents();
5227}
5228
5229/**
5230 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5231 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5232 */
5233TEST_F(InputDispatcherMultiWindowOcclusionTests,
5234 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5235 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5236 "Window with input channel and NO_INPUT_CHANNEL",
5237 ADISPLAY_ID_DEFAULT);
5238
chaviw3277faf2021-05-19 16:45:23 -05005239 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005240 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5241 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5242
5243 PointF touchedPoint = {10, 10};
5244
5245 NotifyMotionArgs motionArgs =
5246 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5247 ADISPLAY_ID_DEFAULT, {touchedPoint});
5248 mDispatcher->notifyMotion(&motionArgs);
5249
5250 mNoInputWindow->assertNoEvents();
5251 mBottomWindow->assertNoEvents();
5252}
5253
Vishnu Nair958da932020-08-21 17:12:37 -07005254class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5255protected:
5256 std::shared_ptr<FakeApplicationHandle> mApp;
5257 sp<FakeWindowHandle> mWindow;
5258 sp<FakeWindowHandle> mMirror;
5259
5260 virtual void SetUp() override {
5261 InputDispatcherTest::SetUp();
5262 mApp = std::make_shared<FakeApplicationHandle>();
5263 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5264 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5265 mWindow->getToken());
5266 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5267 mWindow->setFocusable(true);
5268 mMirror->setFocusable(true);
5269 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5270 }
5271};
5272
5273TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5274 // Request focus on a mirrored window
5275 setFocusedWindow(mMirror);
5276
5277 // window gets focused
5278 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005279 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5280 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005281 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5282}
5283
5284// A focused & mirrored window remains focused only if the window and its mirror are both
5285// focusable.
5286TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5287 setFocusedWindow(mMirror);
5288
5289 // window gets focused
5290 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005291 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5292 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005293 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005294 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5295 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005296 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5297
5298 mMirror->setFocusable(false);
5299 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5300
5301 // window loses focus since one of the windows associated with the token in not focusable
5302 mWindow->consumeFocusEvent(false);
5303
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005304 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5305 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005306 mWindow->assertNoEvents();
5307}
5308
5309// A focused & mirrored window remains focused until the window and its mirror both become
5310// invisible.
5311TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5312 setFocusedWindow(mMirror);
5313
5314 // window gets focused
5315 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005316 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5317 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005318 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005319 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5320 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005321 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5322
5323 mMirror->setVisible(false);
5324 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5325
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005326 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5327 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005328 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005329 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5330 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005331 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5332
5333 mWindow->setVisible(false);
5334 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5335
5336 // window loses focus only after all windows associated with the token become invisible.
5337 mWindow->consumeFocusEvent(false);
5338
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005339 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5340 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005341 mWindow->assertNoEvents();
5342}
5343
5344// A focused & mirrored window remains focused until both windows are removed.
5345TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5346 setFocusedWindow(mMirror);
5347
5348 // window gets focused
5349 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005350 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5351 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005352 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005353 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5354 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005355 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5356
5357 // single window is removed but the window token remains focused
5358 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5359
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005360 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5361 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005362 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005363 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5364 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005365 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5366
5367 // Both windows are removed
5368 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5369 mWindow->consumeFocusEvent(false);
5370
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005371 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5372 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005373 mWindow->assertNoEvents();
5374}
5375
5376// Focus request can be pending until one window becomes visible.
5377TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5378 // Request focus on an invisible mirror.
5379 mWindow->setVisible(false);
5380 mMirror->setVisible(false);
5381 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5382 setFocusedWindow(mMirror);
5383
5384 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005385 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005386 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005387 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005388
5389 mMirror->setVisible(true);
5390 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5391
5392 // window gets focused
5393 mWindow->consumeFocusEvent(true);
5394 // window gets the pending key event
5395 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5396}
Prabir Pradhan99987712020-11-10 18:43:05 -08005397
5398class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5399protected:
5400 std::shared_ptr<FakeApplicationHandle> mApp;
5401 sp<FakeWindowHandle> mWindow;
5402 sp<FakeWindowHandle> mSecondWindow;
5403
5404 void SetUp() override {
5405 InputDispatcherTest::SetUp();
5406 mApp = std::make_shared<FakeApplicationHandle>();
5407 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5408 mWindow->setFocusable(true);
5409 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5410 mSecondWindow->setFocusable(true);
5411
5412 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5413 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5414
5415 setFocusedWindow(mWindow);
5416 mWindow->consumeFocusEvent(true);
5417 }
5418
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005419 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5420 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005421 mDispatcher->notifyPointerCaptureChanged(&args);
5422 }
5423
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005424 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5425 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005426 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005427 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5428 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005429 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005430 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005431 }
5432};
5433
5434TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5435 // Ensure that capture cannot be obtained for unfocused windows.
5436 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5437 mFakePolicy->assertSetPointerCaptureNotCalled();
5438 mSecondWindow->assertNoEvents();
5439
5440 // Ensure that capture can be enabled from the focus window.
5441 requestAndVerifyPointerCapture(mWindow, true);
5442
5443 // Ensure that capture cannot be disabled from a window that does not have capture.
5444 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5445 mFakePolicy->assertSetPointerCaptureNotCalled();
5446
5447 // Ensure that capture can be disabled from the window with capture.
5448 requestAndVerifyPointerCapture(mWindow, false);
5449}
5450
5451TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005452 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005453
5454 setFocusedWindow(mSecondWindow);
5455
5456 // Ensure that the capture disabled event was sent first.
5457 mWindow->consumeCaptureEvent(false);
5458 mWindow->consumeFocusEvent(false);
5459 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005460 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005461
5462 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005463 notifyPointerCaptureChanged({});
5464 notifyPointerCaptureChanged(request);
5465 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005466 mWindow->assertNoEvents();
5467 mSecondWindow->assertNoEvents();
5468 mFakePolicy->assertSetPointerCaptureNotCalled();
5469}
5470
5471TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005472 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005473
5474 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005475 notifyPointerCaptureChanged({});
5476 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005477
5478 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005479 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005480 mWindow->consumeCaptureEvent(false);
5481 mWindow->assertNoEvents();
5482}
5483
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005484TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5485 requestAndVerifyPointerCapture(mWindow, true);
5486
5487 // The first window loses focus.
5488 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005489 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005490 mWindow->consumeCaptureEvent(false);
5491
5492 // Request Pointer Capture from the second window before the notification from InputReader
5493 // arrives.
5494 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005495 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005496
5497 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005498 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005499
5500 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005501 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005502
5503 mSecondWindow->consumeFocusEvent(true);
5504 mSecondWindow->consumeCaptureEvent(true);
5505}
5506
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005507TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5508 // App repeatedly enables and disables capture.
5509 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5510 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5511 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5512 mFakePolicy->assertSetPointerCaptureCalled(false);
5513 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5514 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5515
5516 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5517 // first request is now stale, this should do nothing.
5518 notifyPointerCaptureChanged(firstRequest);
5519 mWindow->assertNoEvents();
5520
5521 // InputReader notifies that the second request was enabled.
5522 notifyPointerCaptureChanged(secondRequest);
5523 mWindow->consumeCaptureEvent(true);
5524}
5525
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005526class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5527protected:
5528 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005529
5530 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5531 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5532
5533 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5534 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5535
5536 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5537 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5538 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5539 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5540 MAXIMUM_OBSCURING_OPACITY);
5541
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005542 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005543 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005544 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005545
5546 sp<FakeWindowHandle> mTouchWindow;
5547
5548 virtual void SetUp() override {
5549 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005550 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005551 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5552 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5553 }
5554
5555 virtual void TearDown() override {
5556 InputDispatcherTest::TearDown();
5557 mTouchWindow.clear();
5558 }
5559
chaviw3277faf2021-05-19 16:45:23 -05005560 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5561 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005562 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005563 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005564 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005565 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005566 return window;
5567 }
5568
5569 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5570 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5571 sp<FakeWindowHandle> window =
5572 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5573 // Generate an arbitrary PID based on the UID
5574 window->setOwnerInfo(1777 + (uid % 10000), uid);
5575 return window;
5576 }
5577
5578 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5579 NotifyMotionArgs args =
5580 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5581 ADISPLAY_ID_DEFAULT, points);
5582 mDispatcher->notifyMotion(&args);
5583 }
5584};
5585
5586TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005587 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005588 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005589 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005590
5591 touch();
5592
5593 mTouchWindow->assertNoEvents();
5594}
5595
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005596TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005597 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5598 const sp<FakeWindowHandle>& w =
5599 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5600 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5601
5602 touch();
5603
5604 mTouchWindow->assertNoEvents();
5605}
5606
5607TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005608 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5609 const sp<FakeWindowHandle>& w =
5610 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5611 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5612
5613 touch();
5614
5615 w->assertNoEvents();
5616}
5617
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005618TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005619 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5620 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005621
5622 touch();
5623
5624 mTouchWindow->consumeAnyMotionDown();
5625}
5626
5627TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005628 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005629 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005630 w->setFrame(Rect(0, 0, 50, 50));
5631 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005632
5633 touch({PointF{100, 100}});
5634
5635 mTouchWindow->consumeAnyMotionDown();
5636}
5637
5638TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005639 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005640 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005641 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5642
5643 touch();
5644
5645 mTouchWindow->consumeAnyMotionDown();
5646}
5647
5648TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5649 const sp<FakeWindowHandle>& w =
5650 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5651 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005652
5653 touch();
5654
5655 mTouchWindow->consumeAnyMotionDown();
5656}
5657
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005658TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5659 const sp<FakeWindowHandle>& w =
5660 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5661 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5662
5663 touch();
5664
5665 w->assertNoEvents();
5666}
5667
5668/**
5669 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5670 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5671 * window, the occluding window will still receive ACTION_OUTSIDE event.
5672 */
5673TEST_F(InputDispatcherUntrustedTouchesTest,
5674 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5675 const sp<FakeWindowHandle>& w =
5676 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005677 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005678 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5679
5680 touch();
5681
5682 w->consumeMotionOutside();
5683}
5684
5685TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5686 const sp<FakeWindowHandle>& w =
5687 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005688 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005689 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5690
5691 touch();
5692
5693 InputEvent* event = w->consume();
5694 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5695 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5696 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5697 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5698}
5699
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005700TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005701 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005702 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5703 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005704 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5705
5706 touch();
5707
5708 mTouchWindow->consumeAnyMotionDown();
5709}
5710
5711TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5712 const sp<FakeWindowHandle>& w =
5713 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5714 MAXIMUM_OBSCURING_OPACITY);
5715 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005716
5717 touch();
5718
5719 mTouchWindow->consumeAnyMotionDown();
5720}
5721
5722TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005723 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005724 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5725 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005726 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5727
5728 touch();
5729
5730 mTouchWindow->assertNoEvents();
5731}
5732
5733TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5734 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5735 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005736 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5737 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005738 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005739 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5740 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005741 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5742
5743 touch();
5744
5745 mTouchWindow->assertNoEvents();
5746}
5747
5748TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5749 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5750 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005751 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5752 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005753 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005754 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5755 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005756 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5757
5758 touch();
5759
5760 mTouchWindow->consumeAnyMotionDown();
5761}
5762
5763TEST_F(InputDispatcherUntrustedTouchesTest,
5764 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5765 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005766 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5767 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005768 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005769 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5770 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005771 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5772
5773 touch();
5774
5775 mTouchWindow->consumeAnyMotionDown();
5776}
5777
5778TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5779 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005780 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5781 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005782 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005783 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5784 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005785 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005786
5787 touch();
5788
5789 mTouchWindow->assertNoEvents();
5790}
5791
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005792TEST_F(InputDispatcherUntrustedTouchesTest,
5793 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5794 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005795 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5796 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005797 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005798 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5799 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005800 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5801
5802 touch();
5803
5804 mTouchWindow->assertNoEvents();
5805}
5806
5807TEST_F(InputDispatcherUntrustedTouchesTest,
5808 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5809 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005810 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5811 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005812 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005813 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5814 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005815 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5816
5817 touch();
5818
5819 mTouchWindow->consumeAnyMotionDown();
5820}
5821
5822TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5823 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005824 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5825 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005826 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5827
5828 touch();
5829
5830 mTouchWindow->consumeAnyMotionDown();
5831}
5832
5833TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5834 const sp<FakeWindowHandle>& w =
5835 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5836 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5837
5838 touch();
5839
5840 mTouchWindow->consumeAnyMotionDown();
5841}
5842
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005843TEST_F(InputDispatcherUntrustedTouchesTest,
5844 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5845 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5846 const sp<FakeWindowHandle>& w =
5847 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5848 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5849
5850 touch();
5851
5852 mTouchWindow->assertNoEvents();
5853}
5854
5855TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5856 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5857 const sp<FakeWindowHandle>& w =
5858 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5859 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5860
5861 touch();
5862
5863 mTouchWindow->consumeAnyMotionDown();
5864}
5865
5866TEST_F(InputDispatcherUntrustedTouchesTest,
5867 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5868 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5869 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005870 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5871 OPACITY_ABOVE_THRESHOLD);
5872 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5873
5874 touch();
5875
5876 mTouchWindow->consumeAnyMotionDown();
5877}
5878
5879TEST_F(InputDispatcherUntrustedTouchesTest,
5880 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5881 const sp<FakeWindowHandle>& w1 =
5882 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5883 OPACITY_BELOW_THRESHOLD);
5884 const sp<FakeWindowHandle>& w2 =
5885 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5886 OPACITY_BELOW_THRESHOLD);
5887 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5888
5889 touch();
5890
5891 mTouchWindow->assertNoEvents();
5892}
5893
5894/**
5895 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5896 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5897 * (which alone would result in allowing touches) does not affect the blocking behavior.
5898 */
5899TEST_F(InputDispatcherUntrustedTouchesTest,
5900 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5901 const sp<FakeWindowHandle>& wB =
5902 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5903 OPACITY_BELOW_THRESHOLD);
5904 const sp<FakeWindowHandle>& wC =
5905 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5906 OPACITY_BELOW_THRESHOLD);
5907 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5908
5909 touch();
5910
5911 mTouchWindow->assertNoEvents();
5912}
5913
5914/**
5915 * This test is testing that a window from a different UID but with same application token doesn't
5916 * block the touch. Apps can share the application token for close UI collaboration for example.
5917 */
5918TEST_F(InputDispatcherUntrustedTouchesTest,
5919 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5920 const sp<FakeWindowHandle>& w =
5921 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5922 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005923 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5924
5925 touch();
5926
5927 mTouchWindow->consumeAnyMotionDown();
5928}
5929
arthurhungb89ccb02020-12-30 16:19:01 +08005930class InputDispatcherDragTests : public InputDispatcherTest {
5931protected:
5932 std::shared_ptr<FakeApplicationHandle> mApp;
5933 sp<FakeWindowHandle> mWindow;
5934 sp<FakeWindowHandle> mSecondWindow;
5935 sp<FakeWindowHandle> mDragWindow;
5936
5937 void SetUp() override {
5938 InputDispatcherTest::SetUp();
5939 mApp = std::make_shared<FakeApplicationHandle>();
5940 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5941 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005942 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005943
5944 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5945 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005946 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005947
5948 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5949 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5950 }
5951
5952 // Start performing drag, we will create a drag window and transfer touch to it.
5953 void performDrag() {
5954 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5955 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5956 {50, 50}))
5957 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5958
5959 // Window should receive motion event.
5960 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5961
5962 // The drag window covers the entire display
5963 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5964 mDispatcher->setInputWindows(
5965 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5966
5967 // Transfer touch focus to the drag window
5968 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5969 true /* isDragDrop */);
5970 mWindow->consumeMotionCancel();
5971 mDragWindow->consumeMotionDown();
5972 }
arthurhung6d4bed92021-03-17 11:59:33 +08005973
5974 // Start performing drag, we will create a drag window and transfer touch to it.
5975 void performStylusDrag() {
5976 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5977 injectMotionEvent(mDispatcher,
5978 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5979 AINPUT_SOURCE_STYLUS)
5980 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5981 .pointer(PointerBuilder(0,
5982 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5983 .x(50)
5984 .y(50))
5985 .build()));
5986 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5987
5988 // The drag window covers the entire display
5989 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5990 mDispatcher->setInputWindows(
5991 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5992
5993 // Transfer touch focus to the drag window
5994 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5995 true /* isDragDrop */);
5996 mWindow->consumeMotionCancel();
5997 mDragWindow->consumeMotionDown();
5998 }
arthurhungb89ccb02020-12-30 16:19:01 +08005999};
6000
6001TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
6002 performDrag();
6003
6004 // Move on window.
6005 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6006 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6007 ADISPLAY_ID_DEFAULT, {50, 50}))
6008 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6009 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6010 mWindow->consumeDragEvent(false, 50, 50);
6011 mSecondWindow->assertNoEvents();
6012
6013 // Move to another window.
6014 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6015 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6016 ADISPLAY_ID_DEFAULT, {150, 50}))
6017 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6018 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6019 mWindow->consumeDragEvent(true, 150, 50);
6020 mSecondWindow->consumeDragEvent(false, 50, 50);
6021
6022 // Move back to original window.
6023 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6024 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6025 ADISPLAY_ID_DEFAULT, {50, 50}))
6026 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6027 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6028 mWindow->consumeDragEvent(false, 50, 50);
6029 mSecondWindow->consumeDragEvent(true, -50, 50);
6030
6031 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6032 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6033 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6034 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6035 mWindow->assertNoEvents();
6036 mSecondWindow->assertNoEvents();
6037}
6038
arthurhungf452d0b2021-01-06 00:19:52 +08006039TEST_F(InputDispatcherDragTests, DragAndDrop) {
6040 performDrag();
6041
6042 // Move on window.
6043 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6044 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6045 ADISPLAY_ID_DEFAULT, {50, 50}))
6046 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6047 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6048 mWindow->consumeDragEvent(false, 50, 50);
6049 mSecondWindow->assertNoEvents();
6050
6051 // Move to another window.
6052 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6053 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6054 ADISPLAY_ID_DEFAULT, {150, 50}))
6055 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6056 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6057 mWindow->consumeDragEvent(true, 150, 50);
6058 mSecondWindow->consumeDragEvent(false, 50, 50);
6059
6060 // drop to another window.
6061 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6062 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6063 {150, 50}))
6064 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6065 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6066 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6067 mWindow->assertNoEvents();
6068 mSecondWindow->assertNoEvents();
6069}
6070
arthurhung6d4bed92021-03-17 11:59:33 +08006071TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6072 performStylusDrag();
6073
6074 // Move on window and keep button pressed.
6075 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6076 injectMotionEvent(mDispatcher,
6077 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6078 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6079 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6080 .x(50)
6081 .y(50))
6082 .build()))
6083 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6084 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6085 mWindow->consumeDragEvent(false, 50, 50);
6086 mSecondWindow->assertNoEvents();
6087
6088 // Move to another window and release button, expect to drop item.
6089 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6090 injectMotionEvent(mDispatcher,
6091 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6092 .buttonState(0)
6093 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6094 .x(150)
6095 .y(50))
6096 .build()))
6097 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6098 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6099 mWindow->assertNoEvents();
6100 mSecondWindow->assertNoEvents();
6101 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6102
6103 // nothing to the window.
6104 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6105 injectMotionEvent(mDispatcher,
6106 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6107 .buttonState(0)
6108 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6109 .x(150)
6110 .y(50))
6111 .build()))
6112 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6113 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6114 mWindow->assertNoEvents();
6115 mSecondWindow->assertNoEvents();
6116}
6117
Arthur Hung6d0571e2021-04-09 20:18:16 +08006118TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6119 performDrag();
6120
6121 // Set second window invisible.
6122 mSecondWindow->setVisible(false);
6123 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6124
6125 // Move on window.
6126 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6127 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6128 ADISPLAY_ID_DEFAULT, {50, 50}))
6129 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6130 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6131 mWindow->consumeDragEvent(false, 50, 50);
6132 mSecondWindow->assertNoEvents();
6133
6134 // Move to another window.
6135 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6136 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6137 ADISPLAY_ID_DEFAULT, {150, 50}))
6138 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6139 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6140 mWindow->consumeDragEvent(true, 150, 50);
6141 mSecondWindow->assertNoEvents();
6142
6143 // drop to another window.
6144 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6145 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6146 {150, 50}))
6147 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6148 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6149 mFakePolicy->assertDropTargetEquals(nullptr);
6150 mWindow->assertNoEvents();
6151 mSecondWindow->assertNoEvents();
6152}
6153
Vishnu Nair062a8672021-09-03 16:07:44 -07006154class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6155
6156TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6157 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6158 sp<FakeWindowHandle> window =
6159 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6160 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
6161 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6162 window->setFocusable(true);
6163 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6164 setFocusedWindow(window);
6165 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6166
6167 // With the flag set, window should not get any input
6168 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6169 mDispatcher->notifyKey(&keyArgs);
6170 window->assertNoEvents();
6171
6172 NotifyMotionArgs motionArgs =
6173 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6174 ADISPLAY_ID_DEFAULT);
6175 mDispatcher->notifyMotion(&motionArgs);
6176 window->assertNoEvents();
6177
6178 // With the flag cleared, the window should get input
6179 window->setInputFeatures({});
6180 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6181
6182 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6183 mDispatcher->notifyKey(&keyArgs);
6184 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6185
6186 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6187 ADISPLAY_ID_DEFAULT);
6188 mDispatcher->notifyMotion(&motionArgs);
6189 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6190 window->assertNoEvents();
6191}
6192
6193TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6194 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6195 std::make_shared<FakeApplicationHandle>();
6196 sp<FakeWindowHandle> obscuringWindow =
6197 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6198 ADISPLAY_ID_DEFAULT);
6199 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6200 obscuringWindow->setOwnerInfo(111, 111);
6201 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6202 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6203 sp<FakeWindowHandle> window =
6204 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6205 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6206 window->setOwnerInfo(222, 222);
6207 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6208 window->setFocusable(true);
6209 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6210 setFocusedWindow(window);
6211 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6212
6213 // With the flag set, window should not get any input
6214 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6215 mDispatcher->notifyKey(&keyArgs);
6216 window->assertNoEvents();
6217
6218 NotifyMotionArgs motionArgs =
6219 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6220 ADISPLAY_ID_DEFAULT);
6221 mDispatcher->notifyMotion(&motionArgs);
6222 window->assertNoEvents();
6223
6224 // With the flag cleared, the window should get input
6225 window->setInputFeatures({});
6226 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6227
6228 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6229 mDispatcher->notifyKey(&keyArgs);
6230 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6231
6232 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6233 ADISPLAY_ID_DEFAULT);
6234 mDispatcher->notifyMotion(&motionArgs);
6235 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6236 window->assertNoEvents();
6237}
6238
6239TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6240 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6241 std::make_shared<FakeApplicationHandle>();
6242 sp<FakeWindowHandle> obscuringWindow =
6243 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6244 ADISPLAY_ID_DEFAULT);
6245 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6246 obscuringWindow->setOwnerInfo(111, 111);
6247 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6248 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6249 sp<FakeWindowHandle> window =
6250 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6251 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6252 window->setOwnerInfo(222, 222);
6253 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6254 window->setFocusable(true);
6255 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6256 setFocusedWindow(window);
6257 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6258
6259 // With the flag set, window should not get any input
6260 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6261 mDispatcher->notifyKey(&keyArgs);
6262 window->assertNoEvents();
6263
6264 NotifyMotionArgs motionArgs =
6265 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6266 ADISPLAY_ID_DEFAULT);
6267 mDispatcher->notifyMotion(&motionArgs);
6268 window->assertNoEvents();
6269
6270 // When the window is no longer obscured because it went on top, it should get input
6271 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6272
6273 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6274 mDispatcher->notifyKey(&keyArgs);
6275 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6276
6277 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6278 ADISPLAY_ID_DEFAULT);
6279 mDispatcher->notifyMotion(&motionArgs);
6280 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6281 window->assertNoEvents();
6282}
6283
Antonio Kantekf16f2832021-09-28 04:39:20 +00006284class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6285protected:
6286 std::shared_ptr<FakeApplicationHandle> mApp;
6287 sp<FakeWindowHandle> mWindow;
6288 sp<FakeWindowHandle> mSecondWindow;
6289
6290 void SetUp() override {
6291 InputDispatcherTest::SetUp();
6292
6293 mApp = std::make_shared<FakeApplicationHandle>();
6294 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6295 mWindow->setFocusable(true);
6296 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6297 mSecondWindow->setFocusable(true);
6298
6299 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6300 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6301
6302 setFocusedWindow(mWindow);
6303 mWindow->consumeFocusEvent(true);
6304 }
6305
Antonio Kantekea47acb2021-12-23 12:41:25 -08006306 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
6307 mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006308 mWindow->consumeTouchModeEvent(inTouchMode);
6309 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6310 }
6311};
6312
6313TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006314 const WindowInfo& windowInfo = *mWindow->getInfo();
6315 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6316 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006317}
6318
6319TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006320 const WindowInfo& windowInfo = *mWindow->getInfo();
6321 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6322 windowInfo.ownerUid, /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006323 mWindow->assertNoEvents();
6324 mSecondWindow->assertNoEvents();
6325}
6326
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006327class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6328public:
6329 sp<FakeWindowHandle> createSpy(const Flags<WindowInfo::Flag> flags) {
6330 std::shared_ptr<FakeApplicationHandle> application =
6331 std::make_shared<FakeApplicationHandle>();
6332 std::string name = "Fake Spy ";
6333 name += std::to_string(mSpyCount++);
6334 sp<FakeWindowHandle> spy =
6335 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
6336 spy->setInputFeatures(WindowInfo::Feature::SPY);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006337 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006338 spy->addFlags(flags);
6339 return spy;
6340 }
6341
6342 sp<FakeWindowHandle> createForeground() {
6343 std::shared_ptr<FakeApplicationHandle> application =
6344 std::make_shared<FakeApplicationHandle>();
6345 sp<FakeWindowHandle> window =
6346 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
6347 window->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
6348 return window;
6349 }
6350
6351private:
6352 int mSpyCount{0};
6353};
6354
6355/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006356 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6357 */
6358TEST_F(InputDispatcherSpyWindowTest, UntrustedSpy_AbortsDispatcher) {
6359 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6360 spy->setTrustedOverlay(false);
6361 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6362 ".* not a trusted overlay");
6363}
6364
6365/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006366 * Input injection into a display with a spy window but no foreground windows should succeed.
6367 */
6368TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
6369 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6370 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6371
6372 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6373 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6374 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6375 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6376}
6377
6378/**
6379 * Verify the order in which different input windows receive events. The touched foreground window
6380 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6381 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6382 * receive events before ones belows it.
6383 *
6384 * Here, we set up a scenario with four windows in the following Z order from the top:
6385 * spy1, spy2, window, spy3.
6386 * We then inject an event and verify that the foreground "window" receives it first, followed by
6387 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6388 * window.
6389 */
6390TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6391 auto window = createForeground();
6392 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6393 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6394 auto spy3 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6395 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6396 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6397 const size_t numChannels = channels.size();
6398
6399 base::unique_fd epollFd(epoll_create1(0 /*flags*/));
6400 if (!epollFd.ok()) {
6401 FAIL() << "Failed to create epoll fd";
6402 }
6403
6404 for (size_t i = 0; i < numChannels; i++) {
6405 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6406 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6407 FAIL() << "Failed to add fd to epoll";
6408 }
6409 }
6410
6411 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6412 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6413 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6414
6415 std::vector<size_t> eventOrder;
6416 std::vector<struct epoll_event> events(numChannels);
6417 for (;;) {
6418 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6419 (100ms).count());
6420 if (nFds < 0) {
6421 FAIL() << "Failed to call epoll_wait";
6422 }
6423 if (nFds == 0) {
6424 break; // epoll_wait timed out
6425 }
6426 for (int i = 0; i < nFds; i++) {
6427 ASSERT_EQ(EPOLLIN, events[i].events);
6428 eventOrder.push_back(events[i].data.u64);
6429 channels[i]->consumeMotionDown();
6430 }
6431 }
6432
6433 // Verify the order in which the events were received.
6434 EXPECT_EQ(3u, eventOrder.size());
6435 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6436 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6437 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6438}
6439
6440/**
6441 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6442 */
6443TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6444 auto window = createForeground();
6445 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCHABLE);
6446 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6447
6448 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6449 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6450 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6451 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6452 spy->assertNoEvents();
6453}
6454
6455/**
6456 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6457 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6458 * to the window.
6459 */
6460TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6461 auto window = createForeground();
6462 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6463 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6464 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6465
6466 // Inject an event outside the spy window's touchable region.
6467 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6468 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6469 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6470 window->consumeMotionDown();
6471 spy->assertNoEvents();
6472 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6473 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6474 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6475 window->consumeMotionUp();
6476 spy->assertNoEvents();
6477
6478 // Inject an event inside the spy window's touchable region.
6479 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6480 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6481 {5, 10}))
6482 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6483 window->consumeMotionDown();
6484 spy->consumeMotionDown();
6485}
6486
6487/**
6488 * A spy window that is a modal window will receive gestures outside of its frame and touchable
6489 * region.
6490 */
6491TEST_F(InputDispatcherSpyWindowTest, ModalWindow) {
6492 auto window = createForeground();
6493 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6494 // This spy window does not have the NOT_TOUCH_MODAL flag set.
6495 spy->setFrame(Rect{0, 0, 20, 20});
6496 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6497
6498 // Inject an event outside the spy window's frame and touchable region.
6499 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6500 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6501 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6502 window->consumeMotionDown();
6503 spy->consumeMotionDown();
6504}
6505
6506/**
6507 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
6508 * flag.
6509 */
6510TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6511 auto window = createForeground();
6512 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
6513 spy->setFrame(Rect{0, 0, 20, 20});
6514 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6515
6516 // Inject an event outside the spy window's frame and touchable region.
6517 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6518 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6519 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6520 window->consumeMotionDown();
6521 spy->consumeMotionOutside();
6522}
6523
6524/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006525 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6526 * any other windows - including other spy windows - will also be cancelled.
6527 */
6528TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6529 auto window = createForeground();
6530 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6531 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6532 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6533
6534 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6535 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6536 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6537 window->consumeMotionDown();
6538 spy1->consumeMotionDown();
6539 spy2->consumeMotionDown();
6540
6541 // Pilfer pointers from the second spy window.
6542 mDispatcher->pilferPointers(spy2->getToken());
6543 spy2->assertNoEvents();
6544 spy1->consumeMotionCancel();
6545 window->consumeMotionCancel();
6546
6547 // The rest of the gesture should only be sent to the second spy window.
6548 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6549 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6550 ADISPLAY_ID_DEFAULT))
6551 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6552 spy2->consumeMotionMove();
6553 spy1->assertNoEvents();
6554 window->assertNoEvents();
6555}
6556
6557/**
6558 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6559 * pointers that are down within its bounds.
6560 */
6561TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6562 auto windowLeft = createForeground();
6563 windowLeft->setFrame({0, 0, 100, 200});
6564 auto windowRight = createForeground();
6565 windowRight->setFrame({100, 0, 200, 200});
6566 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6567 spy->setFrame({0, 0, 200, 200});
6568 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6569
6570 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6571 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6572 {50, 50}))
6573 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6574 windowLeft->consumeMotionDown();
6575 spy->consumeMotionDown();
6576
6577 const MotionEvent secondFingerDownEvent =
6578 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6579 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6580 AINPUT_SOURCE_TOUCHSCREEN)
6581 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6582 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6583 .pointer(
6584 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6585 .build();
6586 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6587 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6588 InputEventInjectionSync::WAIT_FOR_RESULT))
6589 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6590 windowRight->consumeMotionDown();
6591 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6592}
6593
6594/**
6595 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6596 * the spy should receive the second pointer with ACTION_DOWN.
6597 */
6598TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6599 auto window = createForeground();
6600 window->setFrame({0, 0, 200, 200});
6601 auto spyRight = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6602 spyRight->setFrame({100, 0, 200, 200});
6603 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6604
6605 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6606 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6607 {50, 50}))
6608 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6609 window->consumeMotionDown();
6610 spyRight->assertNoEvents();
6611
6612 const MotionEvent secondFingerDownEvent =
6613 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6614 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6615 AINPUT_SOURCE_TOUCHSCREEN)
6616 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6617 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6618 .pointer(
6619 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6620 .build();
6621 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6622 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6623 InputEventInjectionSync::WAIT_FOR_RESULT))
6624 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6625 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6626 spyRight->consumeMotionDown();
6627}
6628
Prabir Pradhand65552b2021-10-07 11:23:50 -07006629class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6630public:
6631 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6632 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6633 std::make_shared<FakeApplicationHandle>();
6634 sp<FakeWindowHandle> overlay =
6635 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6636 ADISPLAY_ID_DEFAULT);
6637 overlay->setFocusable(false);
6638 overlay->setOwnerInfo(111, 111);
6639 overlay->setFlags(WindowInfo::Flag::NOT_TOUCHABLE | WindowInfo::Flag::SPLIT_TOUCH);
6640 overlay->setInputFeatures(WindowInfo::Feature::INTERCEPTS_STYLUS);
6641 overlay->setTrustedOverlay(true);
6642
6643 std::shared_ptr<FakeApplicationHandle> application =
6644 std::make_shared<FakeApplicationHandle>();
6645 sp<FakeWindowHandle> window =
6646 new FakeWindowHandle(application, mDispatcher, "Application window",
6647 ADISPLAY_ID_DEFAULT);
6648 window->setFocusable(true);
6649 window->setOwnerInfo(222, 222);
6650 window->setFlags(WindowInfo::Flag::SPLIT_TOUCH);
6651
6652 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6653 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6654 setFocusedWindow(window);
6655 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6656 return {std::move(overlay), std::move(window)};
6657 }
6658
6659 void sendFingerEvent(int32_t action) {
6660 NotifyMotionArgs motionArgs =
6661 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6662 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6663 mDispatcher->notifyMotion(&motionArgs);
6664 }
6665
6666 void sendStylusEvent(int32_t action) {
6667 NotifyMotionArgs motionArgs =
6668 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6669 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6670 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6671 mDispatcher->notifyMotion(&motionArgs);
6672 }
6673};
6674
6675TEST_F(InputDispatcherStylusInterceptorTest, UntrustedOverlay_AbortsDispatcher) {
6676 auto [overlay, window] = setupStylusOverlayScenario();
6677 overlay->setTrustedOverlay(false);
6678 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6679 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6680 ".* not a trusted overlay");
6681}
6682
6683TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6684 auto [overlay, window] = setupStylusOverlayScenario();
6685 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6686
6687 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6688 overlay->consumeMotionDown();
6689 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6690 overlay->consumeMotionUp();
6691
6692 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6693 window->consumeMotionDown();
6694 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6695 window->consumeMotionUp();
6696
6697 overlay->assertNoEvents();
6698 window->assertNoEvents();
6699}
6700
6701TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6702 auto [overlay, window] = setupStylusOverlayScenario();
6703 overlay->setInputFeatures(overlay->getInfo()->inputFeatures | WindowInfo::Feature::SPY);
6704 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6705
6706 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6707 overlay->consumeMotionDown();
6708 window->consumeMotionDown();
6709 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6710 overlay->consumeMotionUp();
6711 window->consumeMotionUp();
6712
6713 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6714 window->consumeMotionDown();
6715 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6716 window->consumeMotionUp();
6717
6718 overlay->assertNoEvents();
6719 window->assertNoEvents();
6720}
6721
Antonio Kantekea47acb2021-12-23 12:41:25 -08006722// TODO(b/198487159): Add permission tests for touch mode switch once the validation is put in
6723// place.
6724
Garfield Tane84e6f92019-08-29 17:28:41 -07006725} // namespace android::inputdispatcher