blob: aa2f8326c8fd70e88871881f3686b2f8e7beea56 [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);
3115
3116 // Set focused application.
3117 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003118 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003119
3120 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003121 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003122 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003123 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3124
3125 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003126 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003127 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003128 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3129
3130 SCOPED_TRACE("Disable touch mode");
3131 mDispatcher->setInTouchMode(false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003132 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003133 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003134 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003135 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003136 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3137
3138 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003139 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003140 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003141 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3142
3143 SCOPED_TRACE("Enable touch mode again");
3144 mDispatcher->setInTouchMode(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003145 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003146 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003147 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003148 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003149 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3150
3151 window->assertNoEvents();
3152}
3153
Gang Wange9087892020-01-07 12:17:14 -05003154TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003155 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003156 sp<FakeWindowHandle> window =
3157 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3158
3159 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003160 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003161
Arthur Hung72d8dc32020-03-28 00:48:39 +00003162 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003163 setFocusedWindow(window);
3164
Gang Wange9087892020-01-07 12:17:14 -05003165 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3166
3167 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3168 mDispatcher->notifyKey(&keyArgs);
3169
3170 InputEvent* event = window->consume();
3171 ASSERT_NE(event, nullptr);
3172
3173 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3174 ASSERT_NE(verified, nullptr);
3175 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3176
3177 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3178 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3179 ASSERT_EQ(keyArgs.source, verified->source);
3180 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3181
3182 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3183
3184 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003185 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003186 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003187 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3188 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3189 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3190 ASSERT_EQ(0, verifiedKey.repeatCount);
3191}
3192
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003193TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003194 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003195 sp<FakeWindowHandle> window =
3196 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3197
3198 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3199
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003200 ui::Transform transform;
3201 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3202
3203 gui::DisplayInfo displayInfo;
3204 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3205 displayInfo.transform = transform;
3206
3207 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003208
3209 NotifyMotionArgs motionArgs =
3210 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3211 ADISPLAY_ID_DEFAULT);
3212 mDispatcher->notifyMotion(&motionArgs);
3213
3214 InputEvent* event = window->consume();
3215 ASSERT_NE(event, nullptr);
3216
3217 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3218 ASSERT_NE(verified, nullptr);
3219 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3220
3221 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3222 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3223 EXPECT_EQ(motionArgs.source, verified->source);
3224 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3225
3226 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3227
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003228 const vec2 rawXY =
3229 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3230 motionArgs.pointerCoords[0].getXYValue());
3231 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3232 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003233 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003234 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003235 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003236 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3237 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3238}
3239
chaviw09c8d2d2020-08-24 15:48:26 -07003240/**
3241 * Ensure that separate calls to sign the same data are generating the same key.
3242 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3243 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3244 * tests.
3245 */
3246TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3247 KeyEvent event = getTestKeyEvent();
3248 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3249
3250 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3251 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3252 ASSERT_EQ(hmac1, hmac2);
3253}
3254
3255/**
3256 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3257 */
3258TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3259 KeyEvent event = getTestKeyEvent();
3260 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3261 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3262
3263 verifiedEvent.deviceId += 1;
3264 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3265
3266 verifiedEvent.source += 1;
3267 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3268
3269 verifiedEvent.eventTimeNanos += 1;
3270 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3271
3272 verifiedEvent.displayId += 1;
3273 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3274
3275 verifiedEvent.action += 1;
3276 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3277
3278 verifiedEvent.downTimeNanos += 1;
3279 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3280
3281 verifiedEvent.flags += 1;
3282 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3283
3284 verifiedEvent.keyCode += 1;
3285 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3286
3287 verifiedEvent.scanCode += 1;
3288 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3289
3290 verifiedEvent.metaState += 1;
3291 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3292
3293 verifiedEvent.repeatCount += 1;
3294 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3295}
3296
Vishnu Nair958da932020-08-21 17:12:37 -07003297TEST_F(InputDispatcherTest, SetFocusedWindow) {
3298 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3299 sp<FakeWindowHandle> windowTop =
3300 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3301 sp<FakeWindowHandle> windowSecond =
3302 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3303 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3304
3305 // Top window is also focusable but is not granted focus.
3306 windowTop->setFocusable(true);
3307 windowSecond->setFocusable(true);
3308 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3309 setFocusedWindow(windowSecond);
3310
3311 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003312 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3313 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003314
3315 // Focused window should receive event.
3316 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3317 windowTop->assertNoEvents();
3318}
3319
3320TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3321 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3322 sp<FakeWindowHandle> window =
3323 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3324 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3325
3326 window->setFocusable(true);
3327 // Release channel for window is no longer valid.
3328 window->releaseChannel();
3329 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3330 setFocusedWindow(window);
3331
3332 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003333 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3334 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003335
3336 // window channel is invalid, so it should not receive any input event.
3337 window->assertNoEvents();
3338}
3339
3340TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3341 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3342 sp<FakeWindowHandle> window =
3343 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3344 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3345
3346 // Window is not focusable.
3347 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3348 setFocusedWindow(window);
3349
3350 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003351 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3352 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003353
3354 // window is invalid, so it should not receive any input event.
3355 window->assertNoEvents();
3356}
3357
3358TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3359 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3360 sp<FakeWindowHandle> windowTop =
3361 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3362 sp<FakeWindowHandle> windowSecond =
3363 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3364 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3365
3366 windowTop->setFocusable(true);
3367 windowSecond->setFocusable(true);
3368 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3369 setFocusedWindow(windowTop);
3370 windowTop->consumeFocusEvent(true);
3371
3372 setFocusedWindow(windowSecond, windowTop);
3373 windowSecond->consumeFocusEvent(true);
3374 windowTop->consumeFocusEvent(false);
3375
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003376 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3377 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003378
3379 // Focused window should receive event.
3380 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3381}
3382
3383TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3384 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3385 sp<FakeWindowHandle> windowTop =
3386 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3387 sp<FakeWindowHandle> windowSecond =
3388 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3389 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3390
3391 windowTop->setFocusable(true);
3392 windowSecond->setFocusable(true);
3393 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3394 setFocusedWindow(windowSecond, windowTop);
3395
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003396 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3397 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003398
3399 // Event should be dropped.
3400 windowTop->assertNoEvents();
3401 windowSecond->assertNoEvents();
3402}
3403
3404TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3405 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3406 sp<FakeWindowHandle> window =
3407 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3408 sp<FakeWindowHandle> previousFocusedWindow =
3409 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3410 ADISPLAY_ID_DEFAULT);
3411 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3412
3413 window->setFocusable(true);
3414 previousFocusedWindow->setFocusable(true);
3415 window->setVisible(false);
3416 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3417 setFocusedWindow(previousFocusedWindow);
3418 previousFocusedWindow->consumeFocusEvent(true);
3419
3420 // Requesting focus on invisible window takes focus from currently focused window.
3421 setFocusedWindow(window);
3422 previousFocusedWindow->consumeFocusEvent(false);
3423
3424 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003425 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003426 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003427 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003428
3429 // Window does not get focus event or key down.
3430 window->assertNoEvents();
3431
3432 // Window becomes visible.
3433 window->setVisible(true);
3434 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3435
3436 // Window receives focus event.
3437 window->consumeFocusEvent(true);
3438 // Focused window receives key down.
3439 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3440}
3441
Vishnu Nair599f1412021-06-21 10:39:58 -07003442TEST_F(InputDispatcherTest, DisplayRemoved) {
3443 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3444 sp<FakeWindowHandle> window =
3445 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3446 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3447
3448 // window is granted focus.
3449 window->setFocusable(true);
3450 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3451 setFocusedWindow(window);
3452 window->consumeFocusEvent(true);
3453
3454 // When a display is removed window loses focus.
3455 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3456 window->consumeFocusEvent(false);
3457}
3458
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003459/**
3460 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3461 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3462 * of the 'slipperyEnterWindow'.
3463 *
3464 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3465 * a way so that the touched location is no longer covered by the top window.
3466 *
3467 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3468 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3469 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3470 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3471 * with ACTION_DOWN).
3472 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3473 * window moved itself away from the touched location and had Flag::SLIPPERY.
3474 *
3475 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3476 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3477 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3478 *
3479 * In this test, we ensure that the event received by the bottom window has
3480 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3481 */
3482TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3483 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3484 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3485
3486 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3487 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3488
3489 sp<FakeWindowHandle> slipperyExitWindow =
3490 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003491 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003492 // Make sure this one overlaps the bottom window
3493 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3494 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3495 // one. Windows with the same owner are not considered to be occluding each other.
3496 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3497
3498 sp<FakeWindowHandle> slipperyEnterWindow =
3499 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3500 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3501
3502 mDispatcher->setInputWindows(
3503 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3504
3505 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3506 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3507 ADISPLAY_ID_DEFAULT, {{50, 50}});
3508 mDispatcher->notifyMotion(&args);
3509 slipperyExitWindow->consumeMotionDown();
3510 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3511 mDispatcher->setInputWindows(
3512 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3513
3514 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3515 ADISPLAY_ID_DEFAULT, {{51, 51}});
3516 mDispatcher->notifyMotion(&args);
3517
3518 slipperyExitWindow->consumeMotionCancel();
3519
3520 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3521 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3522}
3523
Garfield Tan1c7bc862020-01-28 13:24:04 -08003524class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3525protected:
3526 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3527 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3528
Chris Yea209fde2020-07-22 13:54:51 -07003529 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003530 sp<FakeWindowHandle> mWindow;
3531
3532 virtual void SetUp() override {
3533 mFakePolicy = new FakeInputDispatcherPolicy();
3534 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003535 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003536 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3537 ASSERT_EQ(OK, mDispatcher->start());
3538
3539 setUpWindow();
3540 }
3541
3542 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003543 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003544 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3545
Vishnu Nair47074b82020-08-14 11:54:47 -07003546 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003547 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003548 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003549 mWindow->consumeFocusEvent(true);
3550 }
3551
Chris Ye2ad95392020-09-01 13:44:44 -07003552 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003553 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003554 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003555 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3556 mDispatcher->notifyKey(&keyArgs);
3557
3558 // Window should receive key down event.
3559 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3560 }
3561
3562 void expectKeyRepeatOnce(int32_t repeatCount) {
3563 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3564 InputEvent* repeatEvent = mWindow->consume();
3565 ASSERT_NE(nullptr, repeatEvent);
3566
3567 uint32_t eventType = repeatEvent->getType();
3568 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3569
3570 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3571 uint32_t eventAction = repeatKeyEvent->getAction();
3572 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3573 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3574 }
3575
Chris Ye2ad95392020-09-01 13:44:44 -07003576 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003577 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003578 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003579 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3580 mDispatcher->notifyKey(&keyArgs);
3581
3582 // Window should receive key down event.
3583 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3584 0 /*expectedFlags*/);
3585 }
3586};
3587
3588TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003589 sendAndConsumeKeyDown(1 /* deviceId */);
3590 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3591 expectKeyRepeatOnce(repeatCount);
3592 }
3593}
3594
3595TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3596 sendAndConsumeKeyDown(1 /* deviceId */);
3597 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3598 expectKeyRepeatOnce(repeatCount);
3599 }
3600 sendAndConsumeKeyDown(2 /* deviceId */);
3601 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003602 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3603 expectKeyRepeatOnce(repeatCount);
3604 }
3605}
3606
3607TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003608 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003609 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003610 sendAndConsumeKeyUp(1 /* deviceId */);
3611 mWindow->assertNoEvents();
3612}
3613
3614TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3615 sendAndConsumeKeyDown(1 /* deviceId */);
3616 expectKeyRepeatOnce(1 /*repeatCount*/);
3617 sendAndConsumeKeyDown(2 /* deviceId */);
3618 expectKeyRepeatOnce(1 /*repeatCount*/);
3619 // Stale key up from device 1.
3620 sendAndConsumeKeyUp(1 /* deviceId */);
3621 // Device 2 is still down, keep repeating
3622 expectKeyRepeatOnce(2 /*repeatCount*/);
3623 expectKeyRepeatOnce(3 /*repeatCount*/);
3624 // Device 2 key up
3625 sendAndConsumeKeyUp(2 /* deviceId */);
3626 mWindow->assertNoEvents();
3627}
3628
3629TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3630 sendAndConsumeKeyDown(1 /* deviceId */);
3631 expectKeyRepeatOnce(1 /*repeatCount*/);
3632 sendAndConsumeKeyDown(2 /* deviceId */);
3633 expectKeyRepeatOnce(1 /*repeatCount*/);
3634 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3635 sendAndConsumeKeyUp(2 /* deviceId */);
3636 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003637 mWindow->assertNoEvents();
3638}
3639
liushenxiang42232912021-05-21 20:24:09 +08003640TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3641 sendAndConsumeKeyDown(DEVICE_ID);
3642 expectKeyRepeatOnce(1 /*repeatCount*/);
3643 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3644 mDispatcher->notifyDeviceReset(&args);
3645 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3646 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3647 mWindow->assertNoEvents();
3648}
3649
Garfield Tan1c7bc862020-01-28 13:24:04 -08003650TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003651 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003652 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3653 InputEvent* repeatEvent = mWindow->consume();
3654 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3655 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3656 IdGenerator::getSource(repeatEvent->getId()));
3657 }
3658}
3659
3660TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003661 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003662
3663 std::unordered_set<int32_t> idSet;
3664 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3665 InputEvent* repeatEvent = mWindow->consume();
3666 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3667 int32_t id = repeatEvent->getId();
3668 EXPECT_EQ(idSet.end(), idSet.find(id));
3669 idSet.insert(id);
3670 }
3671}
3672
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003673/* Test InputDispatcher for MultiDisplay */
3674class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3675public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003676 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003677 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003678
Chris Yea209fde2020-07-22 13:54:51 -07003679 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003680 windowInPrimary =
3681 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003682
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003683 // Set focus window for primary display, but focused display would be second one.
3684 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003685 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003686 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003687 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003688 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003689
Chris Yea209fde2020-07-22 13:54:51 -07003690 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003691 windowInSecondary =
3692 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003693 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003694 // Set focus display to second one.
3695 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3696 // Set focus window for second display.
3697 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003698 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003699 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003700 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003701 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003702 }
3703
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003704 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003705 InputDispatcherTest::TearDown();
3706
Chris Yea209fde2020-07-22 13:54:51 -07003707 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003708 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003709 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003710 windowInSecondary.clear();
3711 }
3712
3713protected:
Chris Yea209fde2020-07-22 13:54:51 -07003714 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003715 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003716 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003717 sp<FakeWindowHandle> windowInSecondary;
3718};
3719
3720TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3721 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003722 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3723 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3724 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003725 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003726 windowInSecondary->assertNoEvents();
3727
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003728 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003729 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3730 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3731 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003732 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003733 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003734}
3735
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003736TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003737 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003738 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3739 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003740 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003741 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003742 windowInSecondary->assertNoEvents();
3743
3744 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003745 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003746 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003747 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003748 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003749
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003750 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003751 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003752
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003753 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003754 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3755 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003756
3757 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003758 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003759 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003760 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003761 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003762 windowInSecondary->assertNoEvents();
3763}
3764
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003765// Test per-display input monitors for motion event.
3766TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003767 FakeMonitorReceiver monitorInPrimary =
3768 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3769 FakeMonitorReceiver monitorInSecondary =
3770 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003771
3772 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003773 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3774 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3775 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003776 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003777 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003778 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003779 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003780
3781 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003782 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3783 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3784 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003785 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003786 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003787 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003788 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003789
3790 // Test inject a non-pointer motion event.
3791 // If specific a display, it will dispatch to the focused window of particular display,
3792 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003793 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3794 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3795 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003796 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003797 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003798 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003799 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003800}
3801
3802// Test per-display input monitors for key event.
3803TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003804 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003805 FakeMonitorReceiver monitorInPrimary =
3806 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3807 FakeMonitorReceiver monitorInSecondary =
3808 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003809
3810 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003811 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3812 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003813 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003814 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003815 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003816 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003817}
3818
Vishnu Nair958da932020-08-21 17:12:37 -07003819TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3820 sp<FakeWindowHandle> secondWindowInPrimary =
3821 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3822 secondWindowInPrimary->setFocusable(true);
3823 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3824 setFocusedWindow(secondWindowInPrimary);
3825 windowInPrimary->consumeFocusEvent(false);
3826 secondWindowInPrimary->consumeFocusEvent(true);
3827
3828 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003829 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3830 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003831 windowInPrimary->assertNoEvents();
3832 windowInSecondary->assertNoEvents();
3833 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3834}
3835
Arthur Hungdfd528e2021-12-08 13:23:04 +00003836TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3837 FakeMonitorReceiver monitorInPrimary =
3838 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3839 FakeMonitorReceiver monitorInSecondary =
3840 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3841
3842 // Test touch down on primary display.
3843 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3844 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3845 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3846 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3847 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3848
3849 // Test touch down on second display.
3850 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3851 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3852 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3853 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3854 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3855
3856 // Trigger cancel touch.
3857 mDispatcher->cancelCurrentTouch();
3858 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3859 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3860 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3861 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3862
3863 // Test inject a move motion event, no window/monitor should receive the event.
3864 ASSERT_EQ(InputEventInjectionResult::FAILED,
3865 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3866 ADISPLAY_ID_DEFAULT, {110, 200}))
3867 << "Inject motion event should return InputEventInjectionResult::FAILED";
3868 windowInPrimary->assertNoEvents();
3869 monitorInPrimary.assertNoEvents();
3870
3871 ASSERT_EQ(InputEventInjectionResult::FAILED,
3872 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3873 SECOND_DISPLAY_ID, {110, 200}))
3874 << "Inject motion event should return InputEventInjectionResult::FAILED";
3875 windowInSecondary->assertNoEvents();
3876 monitorInSecondary.assertNoEvents();
3877}
3878
Jackal Guof9696682018-10-05 12:23:23 +08003879class InputFilterTest : public InputDispatcherTest {
3880protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003881 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3882 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003883 NotifyMotionArgs motionArgs;
3884
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003885 motionArgs =
3886 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003887 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003888 motionArgs =
3889 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003890 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003891 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003892 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003893 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3894 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003895 } else {
3896 mFakePolicy->assertFilterInputEventWasNotCalled();
3897 }
3898 }
3899
3900 void testNotifyKey(bool expectToBeFiltered) {
3901 NotifyKeyArgs keyArgs;
3902
3903 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3904 mDispatcher->notifyKey(&keyArgs);
3905 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3906 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003907 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003908
3909 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003910 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003911 } else {
3912 mFakePolicy->assertFilterInputEventWasNotCalled();
3913 }
3914 }
3915};
3916
3917// Test InputFilter for MotionEvent
3918TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3919 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3920 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3921 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3922
3923 // Enable InputFilter
3924 mDispatcher->setInputFilterEnabled(true);
3925 // Test touch on both primary and second display, and check if both events are filtered.
3926 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3927 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3928
3929 // Disable InputFilter
3930 mDispatcher->setInputFilterEnabled(false);
3931 // Test touch on both primary and second display, and check if both events aren't filtered.
3932 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3933 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3934}
3935
3936// Test InputFilter for KeyEvent
3937TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3938 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3939 testNotifyKey(/*expectToBeFiltered*/ false);
3940
3941 // Enable InputFilter
3942 mDispatcher->setInputFilterEnabled(true);
3943 // Send a key event, and check if it is filtered.
3944 testNotifyKey(/*expectToBeFiltered*/ true);
3945
3946 // Disable InputFilter
3947 mDispatcher->setInputFilterEnabled(false);
3948 // Send a key event, and check if it isn't filtered.
3949 testNotifyKey(/*expectToBeFiltered*/ false);
3950}
3951
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003952// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3953// logical display coordinate space.
3954TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3955 ui::Transform firstDisplayTransform;
3956 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3957 ui::Transform secondDisplayTransform;
3958 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3959
3960 std::vector<gui::DisplayInfo> displayInfos(2);
3961 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3962 displayInfos[0].transform = firstDisplayTransform;
3963 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3964 displayInfos[1].transform = secondDisplayTransform;
3965
3966 mDispatcher->onWindowInfosChanged({}, displayInfos);
3967
3968 // Enable InputFilter
3969 mDispatcher->setInputFilterEnabled(true);
3970
3971 // Ensure the correct transforms are used for the displays.
3972 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3973 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3974}
3975
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003976class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3977protected:
3978 virtual void SetUp() override {
3979 InputDispatcherTest::SetUp();
3980
3981 /**
3982 * We don't need to enable input filter to test the injected event policy, but we enabled it
3983 * here to make the tests more realistic, since this policy only matters when inputfilter is
3984 * on.
3985 */
3986 mDispatcher->setInputFilterEnabled(true);
3987
3988 std::shared_ptr<InputApplicationHandle> application =
3989 std::make_shared<FakeApplicationHandle>();
3990 mWindow =
3991 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3992
3993 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3994 mWindow->setFocusable(true);
3995 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3996 setFocusedWindow(mWindow);
3997 mWindow->consumeFocusEvent(true);
3998 }
3999
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004000 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4001 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004002 KeyEvent event;
4003
4004 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4005 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4006 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4007 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4008 const int32_t additionalPolicyFlags =
4009 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4010 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4011 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
4012 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4013 policyFlags | additionalPolicyFlags));
4014
4015 InputEvent* received = mWindow->consume();
4016 ASSERT_NE(nullptr, received);
4017 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004018 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4019 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4020 ASSERT_EQ(flags, keyEvent.getFlags());
4021 }
4022
4023 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4024 int32_t flags) {
4025 MotionEvent event;
4026 PointerProperties pointerProperties[1];
4027 PointerCoords pointerCoords[1];
4028 pointerProperties[0].clear();
4029 pointerProperties[0].id = 0;
4030 pointerCoords[0].clear();
4031 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4032 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4033
4034 ui::Transform identityTransform;
4035 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4036 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4037 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4038 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4039 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004040 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004041 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004042 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4043
4044 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4045 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4046 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
4047 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4048 policyFlags | additionalPolicyFlags));
4049
4050 InputEvent* received = mWindow->consume();
4051 ASSERT_NE(nullptr, received);
4052 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4053 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4054 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4055 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004056 }
4057
4058private:
4059 sp<FakeWindowHandle> mWindow;
4060};
4061
4062TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004063 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4064 // filter. Without it, the event will no different from a regularly injected event, and the
4065 // injected device id will be overwritten.
4066 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4067 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004068}
4069
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004070TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004071 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004072 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4073 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4074}
4075
4076TEST_F(InputFilterInjectionPolicyTest,
4077 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4078 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4079 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4080 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004081}
4082
4083TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4084 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004085 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004086}
4087
chaviwfd6d3512019-03-25 13:23:49 -07004088class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004089 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004090 InputDispatcherTest::SetUp();
4091
Chris Yea209fde2020-07-22 13:54:51 -07004092 std::shared_ptr<FakeApplicationHandle> application =
4093 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004094 mUnfocusedWindow =
4095 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004096 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4097 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4098 // window.
chaviw3277faf2021-05-19 16:45:23 -05004099 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07004100
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004101 mFocusedWindow =
4102 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4103 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004104 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07004105
4106 // Set focused application.
4107 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004108 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004109
4110 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004111 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004112 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004113 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004114 }
4115
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004116 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004117 InputDispatcherTest::TearDown();
4118
4119 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004120 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004121 }
4122
4123protected:
4124 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004125 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004126 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004127};
4128
4129// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4130// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4131// the onPointerDownOutsideFocus callback.
4132TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004133 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004134 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4135 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004136 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004137 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004138
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004139 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004140 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4141}
4142
4143// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4144// DOWN on the window that doesn't have focus. Ensure no window received the
4145// onPointerDownOutsideFocus callback.
4146TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004147 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004148 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004149 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004150 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004151
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004152 ASSERT_TRUE(mDispatcher->waitForIdle());
4153 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004154}
4155
4156// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4157// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4158TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004159 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4160 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004161 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004162 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004163
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004164 ASSERT_TRUE(mDispatcher->waitForIdle());
4165 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004166}
4167
4168// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4169// DOWN on the window that already has focus. Ensure no window received the
4170// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004171TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004172 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004173 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004174 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004175 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004176 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004177
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004178 ASSERT_TRUE(mDispatcher->waitForIdle());
4179 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004180}
4181
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004182// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4183// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4184TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4185 const MotionEvent event =
4186 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4187 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4188 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4189 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4190 .build();
4191 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4192 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4193 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4194
4195 ASSERT_TRUE(mDispatcher->waitForIdle());
4196 mFakePolicy->assertOnPointerDownWasNotCalled();
4197 // Ensure that the unfocused window did not receive any FOCUS events.
4198 mUnfocusedWindow->assertNoEvents();
4199}
4200
chaviwaf87b3e2019-10-01 16:59:28 -07004201// These tests ensures we can send touch events to a single client when there are multiple input
4202// windows that point to the same client token.
4203class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4204 virtual void SetUp() override {
4205 InputDispatcherTest::SetUp();
4206
Chris Yea209fde2020-07-22 13:54:51 -07004207 std::shared_ptr<FakeApplicationHandle> application =
4208 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004209 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4210 ADISPLAY_ID_DEFAULT);
4211 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
4212 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05004213 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004214 mWindow1->setFrame(Rect(0, 0, 100, 100));
4215
4216 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4217 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05004218 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004219 mWindow2->setFrame(Rect(100, 100, 200, 200));
4220
Arthur Hung72d8dc32020-03-28 00:48:39 +00004221 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004222 }
4223
4224protected:
4225 sp<FakeWindowHandle> mWindow1;
4226 sp<FakeWindowHandle> mWindow2;
4227
4228 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004229 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004230 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4231 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004232 }
4233
4234 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4235 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004236 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004237 InputEvent* event = window->consume();
4238
4239 ASSERT_NE(nullptr, event) << name.c_str()
4240 << ": consumer should have returned non-NULL event.";
4241
4242 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4243 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4244 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4245
4246 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004247 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004248
4249 for (size_t i = 0; i < points.size(); i++) {
4250 float expectedX = points[i].x;
4251 float expectedY = points[i].y;
4252
4253 EXPECT_EQ(expectedX, motionEvent.getX(i))
4254 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4255 << ", got " << motionEvent.getX(i);
4256 EXPECT_EQ(expectedY, motionEvent.getY(i))
4257 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4258 << ", got " << motionEvent.getY(i);
4259 }
4260 }
chaviw9eaa22c2020-07-01 16:21:27 -07004261
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004262 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004263 std::vector<PointF> expectedPoints) {
4264 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4265 ADISPLAY_ID_DEFAULT, touchedPoints);
4266 mDispatcher->notifyMotion(&motionArgs);
4267
4268 // Always consume from window1 since it's the window that has the InputReceiver
4269 consumeMotionEvent(mWindow1, action, expectedPoints);
4270 }
chaviwaf87b3e2019-10-01 16:59:28 -07004271};
4272
4273TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4274 // Touch Window 1
4275 PointF touchedPoint = {10, 10};
4276 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004277 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004278
4279 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004280 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004281
4282 // Touch Window 2
4283 touchedPoint = {150, 150};
4284 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004285 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004286}
4287
chaviw9eaa22c2020-07-01 16:21:27 -07004288TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4289 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004290 mWindow2->setWindowScale(0.5f, 0.5f);
4291
4292 // Touch Window 1
4293 PointF touchedPoint = {10, 10};
4294 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004295 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004296 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004297 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004298
4299 // Touch Window 2
4300 touchedPoint = {150, 150};
4301 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004302 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4303 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004304
chaviw9eaa22c2020-07-01 16:21:27 -07004305 // Update the transform so rotation is set
4306 mWindow2->setWindowTransform(0, -1, 1, 0);
4307 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4308 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004309}
4310
chaviw9eaa22c2020-07-01 16:21:27 -07004311TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004312 mWindow2->setWindowScale(0.5f, 0.5f);
4313
4314 // Touch Window 1
4315 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4316 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004317 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004318
4319 // Touch Window 2
4320 int32_t actionPointerDown =
4321 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004322 touchedPoints.push_back(PointF{150, 150});
4323 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4324 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004325
chaviw9eaa22c2020-07-01 16:21:27 -07004326 // Release Window 2
4327 int32_t actionPointerUp =
4328 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4329 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4330 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004331
chaviw9eaa22c2020-07-01 16:21:27 -07004332 // Update the transform so rotation is set for Window 2
4333 mWindow2->setWindowTransform(0, -1, 1, 0);
4334 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4335 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004336}
4337
chaviw9eaa22c2020-07-01 16:21:27 -07004338TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004339 mWindow2->setWindowScale(0.5f, 0.5f);
4340
4341 // Touch Window 1
4342 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4343 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004344 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004345
4346 // Touch Window 2
4347 int32_t actionPointerDown =
4348 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004349 touchedPoints.push_back(PointF{150, 150});
4350 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004351
chaviw9eaa22c2020-07-01 16:21:27 -07004352 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004353
4354 // Move both windows
4355 touchedPoints = {{20, 20}, {175, 175}};
4356 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4357 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4358
chaviw9eaa22c2020-07-01 16:21:27 -07004359 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004360
chaviw9eaa22c2020-07-01 16:21:27 -07004361 // Release Window 2
4362 int32_t actionPointerUp =
4363 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4364 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4365 expectedPoints.pop_back();
4366
4367 // Touch Window 2
4368 mWindow2->setWindowTransform(0, -1, 1, 0);
4369 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4370 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4371
4372 // Move both windows
4373 touchedPoints = {{20, 20}, {175, 175}};
4374 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4375 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4376
4377 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004378}
4379
4380TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4381 mWindow1->setWindowScale(0.5f, 0.5f);
4382
4383 // Touch Window 1
4384 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4385 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004386 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004387
4388 // Touch Window 2
4389 int32_t actionPointerDown =
4390 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004391 touchedPoints.push_back(PointF{150, 150});
4392 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004393
chaviw9eaa22c2020-07-01 16:21:27 -07004394 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004395
4396 // Move both windows
4397 touchedPoints = {{20, 20}, {175, 175}};
4398 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4399 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4400
chaviw9eaa22c2020-07-01 16:21:27 -07004401 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004402}
4403
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004404class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4405 virtual void SetUp() override {
4406 InputDispatcherTest::SetUp();
4407
Chris Yea209fde2020-07-22 13:54:51 -07004408 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004409 mApplication->setDispatchingTimeout(20ms);
4410 mWindow =
4411 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4412 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004413 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004414 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004415 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4416 // window.
chaviw3277faf2021-05-19 16:45:23 -05004417 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004418
4419 // Set focused application.
4420 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4421
4422 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004423 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004424 mWindow->consumeFocusEvent(true);
4425 }
4426
4427 virtual void TearDown() override {
4428 InputDispatcherTest::TearDown();
4429 mWindow.clear();
4430 }
4431
4432protected:
Chris Yea209fde2020-07-22 13:54:51 -07004433 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004434 sp<FakeWindowHandle> mWindow;
4435 static constexpr PointF WINDOW_LOCATION = {20, 20};
4436
4437 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004438 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004439 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4440 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004441 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004442 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4443 WINDOW_LOCATION));
4444 }
4445};
4446
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004447// Send a tap and respond, which should not cause an ANR.
4448TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4449 tapOnWindow();
4450 mWindow->consumeMotionDown();
4451 mWindow->consumeMotionUp();
4452 ASSERT_TRUE(mDispatcher->waitForIdle());
4453 mFakePolicy->assertNotifyAnrWasNotCalled();
4454}
4455
4456// Send a regular key and respond, which should not cause an ANR.
4457TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004458 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004459 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4460 ASSERT_TRUE(mDispatcher->waitForIdle());
4461 mFakePolicy->assertNotifyAnrWasNotCalled();
4462}
4463
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004464TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4465 mWindow->setFocusable(false);
4466 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4467 mWindow->consumeFocusEvent(false);
4468
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004469 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004470 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004471 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4472 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004473 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004474 // Key will not go to window because we have no focused window.
4475 // The 'no focused window' ANR timer should start instead.
4476
4477 // Now, the focused application goes away.
4478 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4479 // The key should get dropped and there should be no ANR.
4480
4481 ASSERT_TRUE(mDispatcher->waitForIdle());
4482 mFakePolicy->assertNotifyAnrWasNotCalled();
4483}
4484
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004485// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004486// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4487// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004488TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004489 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004490 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4491 WINDOW_LOCATION));
4492
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004493 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4494 ASSERT_TRUE(sequenceNum);
4495 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004496 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004497
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004498 mWindow->finishEvent(*sequenceNum);
4499 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4500 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004501 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004502 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004503}
4504
4505// Send a key to the app and have the app not respond right away.
4506TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4507 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004508 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004509 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4510 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004511 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004512 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004513 ASSERT_TRUE(mDispatcher->waitForIdle());
4514}
4515
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004516// We have a focused application, but no focused window
4517TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004518 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004519 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4520 mWindow->consumeFocusEvent(false);
4521
4522 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004523 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004524 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4525 WINDOW_LOCATION));
4526 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4527 mDispatcher->waitForIdle();
4528 mFakePolicy->assertNotifyAnrWasNotCalled();
4529
4530 // Once a focused event arrives, we get an ANR for this application
4531 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4532 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004533 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004534 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004535 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004536 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004537 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004538 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004539 ASSERT_TRUE(mDispatcher->waitForIdle());
4540}
4541
4542// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004543// Make sure that we don't notify policy twice about the same ANR.
4544TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004545 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004546 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4547 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004548
4549 // Once a focused event arrives, we get an ANR for this application
4550 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4551 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004552 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004553 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004554 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004555 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004556 const std::chrono::duration appTimeout =
4557 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004558 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004559
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004560 std::this_thread::sleep_for(appTimeout);
4561 // ANR should not be raised again. It is up to policy to do that if it desires.
4562 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004563
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004564 // If we now get a focused window, the ANR should stop, but the policy handles that via
4565 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004566 ASSERT_TRUE(mDispatcher->waitForIdle());
4567}
4568
4569// We have a focused application, but no focused window
4570TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004571 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004572 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4573 mWindow->consumeFocusEvent(false);
4574
4575 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004576 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004577 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004578 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4579 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004580
4581 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004582 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004583
4584 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004585 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004586 ASSERT_TRUE(mDispatcher->waitForIdle());
4587 mWindow->assertNoEvents();
4588}
4589
4590/**
4591 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4592 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4593 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4594 * the ANR mechanism should still work.
4595 *
4596 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4597 * DOWN event, while not responding on the second one.
4598 */
4599TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4600 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4601 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4602 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4603 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4604 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004605 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004606
4607 // Now send ACTION_UP, with identical timestamp
4608 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4609 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4610 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4611 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004612 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004613
4614 // We have now sent down and up. Let's consume first event and then ANR on the second.
4615 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4616 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004617 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004618}
4619
4620// If an app is not responding to a key event, gesture monitors should continue to receive
4621// new motion events
4622TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
4623 FakeMonitorReceiver monitor =
4624 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4625 true /*isGestureMonitor*/);
4626
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004627 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4628 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004629 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004630 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004631
4632 // Stuck on the ACTION_UP
4633 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004634 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004635
4636 // New tap will go to the gesture monitor, but not to the window
4637 tapOnWindow();
4638 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4639 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4640
4641 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4642 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004643 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004644 mWindow->assertNoEvents();
4645 monitor.assertNoEvents();
4646}
4647
4648// If an app is not responding to a motion event, gesture monitors should continue to receive
4649// new motion events
4650TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
4651 FakeMonitorReceiver monitor =
4652 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4653 true /*isGestureMonitor*/);
4654
4655 tapOnWindow();
4656 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4657 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4658
4659 mWindow->consumeMotionDown();
4660 // Stuck on the ACTION_UP
4661 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004662 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004663
4664 // New tap will go to the gesture monitor, but not to the window
4665 tapOnWindow();
4666 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4667 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4668
4669 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4670 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004671 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004672 mWindow->assertNoEvents();
4673 monitor.assertNoEvents();
4674}
4675
4676// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4677// process events, you don't get an anr. When the window later becomes unresponsive again, you
4678// get an ANR again.
4679// 1. tap -> block on ACTION_UP -> receive ANR
4680// 2. consume all pending events (= queue becomes healthy again)
4681// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4682TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4683 tapOnWindow();
4684
4685 mWindow->consumeMotionDown();
4686 // Block on ACTION_UP
4687 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004688 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004689 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4690 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004691 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004692 mWindow->assertNoEvents();
4693
4694 tapOnWindow();
4695 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004696 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004697 mWindow->consumeMotionUp();
4698
4699 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004700 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004701 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004702 mWindow->assertNoEvents();
4703}
4704
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004705// If a connection remains unresponsive for a while, make sure policy is only notified once about
4706// it.
4707TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004708 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004709 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4710 WINDOW_LOCATION));
4711
4712 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004713 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004714 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004715 // 'notifyConnectionUnresponsive' should only be called once per connection
4716 mFakePolicy->assertNotifyAnrWasNotCalled();
4717 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004718 mWindow->consumeMotionDown();
4719 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4720 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4721 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004722 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004723 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004724 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004725}
4726
4727/**
4728 * If a window is processing a motion event, and then a key event comes in, the key event should
4729 * not to to the focused window until the motion is processed.
4730 *
4731 * Warning!!!
4732 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4733 * and the injection timeout that we specify when injecting the key.
4734 * We must have the injection timeout (10ms) be smaller than
4735 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4736 *
4737 * If that value changes, this test should also change.
4738 */
4739TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4740 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4741 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4742
4743 tapOnWindow();
4744 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4745 ASSERT_TRUE(downSequenceNum);
4746 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4747 ASSERT_TRUE(upSequenceNum);
4748 // Don't finish the events yet, and send a key
4749 // Injection will "succeed" because we will eventually give up and send the key to the focused
4750 // window even if motions are still being processed. But because the injection timeout is short,
4751 // we will receive INJECTION_TIMED_OUT as the result.
4752
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004753 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004754 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004755 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4756 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004757 // Key will not be sent to the window, yet, because the window is still processing events
4758 // and the key remains pending, waiting for the touch events to be processed
4759 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4760 ASSERT_FALSE(keySequenceNum);
4761
4762 std::this_thread::sleep_for(500ms);
4763 // if we wait long enough though, dispatcher will give up, and still send the key
4764 // to the focused window, even though we have not yet finished the motion event
4765 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4766 mWindow->finishEvent(*downSequenceNum);
4767 mWindow->finishEvent(*upSequenceNum);
4768}
4769
4770/**
4771 * If a window is processing a motion event, and then a key event comes in, the key event should
4772 * not go to the focused window until the motion is processed.
4773 * If then a new motion comes in, then the pending key event should be going to the currently
4774 * focused window right away.
4775 */
4776TEST_F(InputDispatcherSingleWindowAnr,
4777 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4778 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4779 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4780
4781 tapOnWindow();
4782 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4783 ASSERT_TRUE(downSequenceNum);
4784 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4785 ASSERT_TRUE(upSequenceNum);
4786 // Don't finish the events yet, and send a key
4787 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004788 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004789 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004790 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004791 // At this point, key is still pending, and should not be sent to the application yet.
4792 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4793 ASSERT_FALSE(keySequenceNum);
4794
4795 // Now tap down again. It should cause the pending key to go to the focused window right away.
4796 tapOnWindow();
4797 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4798 // the other events yet. We can finish events in any order.
4799 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4800 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4801 mWindow->consumeMotionDown();
4802 mWindow->consumeMotionUp();
4803 mWindow->assertNoEvents();
4804}
4805
4806class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4807 virtual void SetUp() override {
4808 InputDispatcherTest::SetUp();
4809
Chris Yea209fde2020-07-22 13:54:51 -07004810 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004811 mApplication->setDispatchingTimeout(10ms);
4812 mUnfocusedWindow =
4813 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4814 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4815 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4816 // window.
4817 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004818 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4819 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4820 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004821
4822 mFocusedWindow =
4823 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004824 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004825 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004826 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004827
4828 // Set focused application.
4829 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004830 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004831
4832 // Expect one focus window exist in display.
4833 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004834 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004835 mFocusedWindow->consumeFocusEvent(true);
4836 }
4837
4838 virtual void TearDown() override {
4839 InputDispatcherTest::TearDown();
4840
4841 mUnfocusedWindow.clear();
4842 mFocusedWindow.clear();
4843 }
4844
4845protected:
Chris Yea209fde2020-07-22 13:54:51 -07004846 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004847 sp<FakeWindowHandle> mUnfocusedWindow;
4848 sp<FakeWindowHandle> mFocusedWindow;
4849 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4850 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4851 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4852
4853 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4854
4855 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4856
4857private:
4858 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004859 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004860 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4861 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004862 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004863 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4864 location));
4865 }
4866};
4867
4868// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4869// should be ANR'd first.
4870TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004871 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004872 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4873 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004874 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004875 mFocusedWindow->consumeMotionDown();
4876 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4877 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4878 // We consumed all events, so no ANR
4879 ASSERT_TRUE(mDispatcher->waitForIdle());
4880 mFakePolicy->assertNotifyAnrWasNotCalled();
4881
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004882 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004883 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4884 FOCUSED_WINDOW_LOCATION));
4885 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4886 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004887
4888 const std::chrono::duration timeout =
4889 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004890 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004891 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4892 // sequence to make it consistent
4893 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004894 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004895 mFocusedWindow->consumeMotionDown();
4896 // This cancel is generated because the connection was unresponsive
4897 mFocusedWindow->consumeMotionCancel();
4898 mFocusedWindow->assertNoEvents();
4899 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004900 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004901 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004902 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004903}
4904
4905// If we have 2 windows with identical timeouts that are both unresponsive,
4906// it doesn't matter which order they should have ANR.
4907// But we should receive ANR for both.
4908TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4909 // Set the timeout for unfocused window to match the focused window
4910 mUnfocusedWindow->setDispatchingTimeout(10ms);
4911 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4912
4913 tapOnFocusedWindow();
4914 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004915 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4916 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004917
4918 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004919 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4920 mFocusedWindow->getToken() == anrConnectionToken2);
4921 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4922 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004923
4924 ASSERT_TRUE(mDispatcher->waitForIdle());
4925 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004926
4927 mFocusedWindow->consumeMotionDown();
4928 mFocusedWindow->consumeMotionUp();
4929 mUnfocusedWindow->consumeMotionOutside();
4930
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004931 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4932 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004933
4934 // Both applications should be marked as responsive, in any order
4935 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4936 mFocusedWindow->getToken() == responsiveToken2);
4937 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4938 mUnfocusedWindow->getToken() == responsiveToken2);
4939 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004940}
4941
4942// If a window is already not responding, the second tap on the same window should be ignored.
4943// We should also log an error to account for the dropped event (not tested here).
4944// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4945TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4946 tapOnFocusedWindow();
4947 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4948 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4949 // Receive the events, but don't respond
4950 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4951 ASSERT_TRUE(downEventSequenceNum);
4952 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4953 ASSERT_TRUE(upEventSequenceNum);
4954 const std::chrono::duration timeout =
4955 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004956 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004957
4958 // Tap once again
4959 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004960 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004961 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4962 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004963 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004964 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4965 FOCUSED_WINDOW_LOCATION));
4966 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4967 // valid touch target
4968 mUnfocusedWindow->assertNoEvents();
4969
4970 // Consume the first tap
4971 mFocusedWindow->finishEvent(*downEventSequenceNum);
4972 mFocusedWindow->finishEvent(*upEventSequenceNum);
4973 ASSERT_TRUE(mDispatcher->waitForIdle());
4974 // The second tap did not go to the focused window
4975 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004976 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004977 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004978 mFakePolicy->assertNotifyAnrWasNotCalled();
4979}
4980
4981// If you tap outside of all windows, there will not be ANR
4982TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004983 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004984 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4985 LOCATION_OUTSIDE_ALL_WINDOWS));
4986 ASSERT_TRUE(mDispatcher->waitForIdle());
4987 mFakePolicy->assertNotifyAnrWasNotCalled();
4988}
4989
4990// Since the focused window is paused, tapping on it should not produce any events
4991TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4992 mFocusedWindow->setPaused(true);
4993 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4994
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004995 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004996 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4997 FOCUSED_WINDOW_LOCATION));
4998
4999 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5000 ASSERT_TRUE(mDispatcher->waitForIdle());
5001 // Should not ANR because the window is paused, and touches shouldn't go to it
5002 mFakePolicy->assertNotifyAnrWasNotCalled();
5003
5004 mFocusedWindow->assertNoEvents();
5005 mUnfocusedWindow->assertNoEvents();
5006}
5007
5008/**
5009 * If a window is processing a motion event, and then a key event comes in, the key event should
5010 * not to to the focused window until the motion is processed.
5011 * If a different window becomes focused at this time, the key should go to that window instead.
5012 *
5013 * Warning!!!
5014 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5015 * and the injection timeout that we specify when injecting the key.
5016 * We must have the injection timeout (10ms) be smaller than
5017 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5018 *
5019 * If that value changes, this test should also change.
5020 */
5021TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5022 // Set a long ANR timeout to prevent it from triggering
5023 mFocusedWindow->setDispatchingTimeout(2s);
5024 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5025
5026 tapOnUnfocusedWindow();
5027 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5028 ASSERT_TRUE(downSequenceNum);
5029 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5030 ASSERT_TRUE(upSequenceNum);
5031 // Don't finish the events yet, and send a key
5032 // Injection will succeed because we will eventually give up and send the key to the focused
5033 // window even if motions are still being processed.
5034
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005035 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005036 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005037 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5038 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005039 // Key will not be sent to the window, yet, because the window is still processing events
5040 // and the key remains pending, waiting for the touch events to be processed
5041 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5042 ASSERT_FALSE(keySequenceNum);
5043
5044 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005045 mFocusedWindow->setFocusable(false);
5046 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005047 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005048 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005049
5050 // Focus events should precede the key events
5051 mUnfocusedWindow->consumeFocusEvent(true);
5052 mFocusedWindow->consumeFocusEvent(false);
5053
5054 // Finish the tap events, which should unblock dispatcher
5055 mUnfocusedWindow->finishEvent(*downSequenceNum);
5056 mUnfocusedWindow->finishEvent(*upSequenceNum);
5057
5058 // Now that all queues are cleared and no backlog in the connections, the key event
5059 // can finally go to the newly focused "mUnfocusedWindow".
5060 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5061 mFocusedWindow->assertNoEvents();
5062 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005063 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005064}
5065
5066// When the touch stream is split across 2 windows, and one of them does not respond,
5067// then ANR should be raised and the touch should be canceled for the unresponsive window.
5068// The other window should not be affected by that.
5069TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5070 // Touch Window 1
5071 NotifyMotionArgs motionArgs =
5072 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5073 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5074 mDispatcher->notifyMotion(&motionArgs);
5075 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5076 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5077
5078 // Touch Window 2
5079 int32_t actionPointerDown =
5080 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
5081
5082 motionArgs =
5083 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5084 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
5085 mDispatcher->notifyMotion(&motionArgs);
5086
5087 const std::chrono::duration timeout =
5088 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005089 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005090
5091 mUnfocusedWindow->consumeMotionDown();
5092 mFocusedWindow->consumeMotionDown();
5093 // Focused window may or may not receive ACTION_MOVE
5094 // But it should definitely receive ACTION_CANCEL due to the ANR
5095 InputEvent* event;
5096 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5097 ASSERT_TRUE(moveOrCancelSequenceNum);
5098 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5099 ASSERT_NE(nullptr, event);
5100 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5101 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5102 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5103 mFocusedWindow->consumeMotionCancel();
5104 } else {
5105 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5106 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005107 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005108 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005109
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005110 mUnfocusedWindow->assertNoEvents();
5111 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005112 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005113}
5114
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005115/**
5116 * If we have no focused window, and a key comes in, we start the ANR timer.
5117 * The focused application should add a focused window before the timer runs out to prevent ANR.
5118 *
5119 * If the user touches another application during this time, the key should be dropped.
5120 * Next, if a new focused window comes in, without toggling the focused application,
5121 * then no ANR should occur.
5122 *
5123 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5124 * but in some cases the policy may not update the focused application.
5125 */
5126TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5127 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5128 std::make_shared<FakeApplicationHandle>();
5129 focusedApplication->setDispatchingTimeout(60ms);
5130 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5131 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5132 mFocusedWindow->setFocusable(false);
5133
5134 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5135 mFocusedWindow->consumeFocusEvent(false);
5136
5137 // Send a key. The ANR timer should start because there is no focused window.
5138 // 'focusedApplication' will get blamed if this timer completes.
5139 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005140 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005141 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005142 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5143 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005144 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005145
5146 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5147 // then the injected touches won't cause the focused event to get dropped.
5148 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5149 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5150 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5151 // For this test, it means that the key would get delivered to the window once it becomes
5152 // focused.
5153 std::this_thread::sleep_for(10ms);
5154
5155 // Touch unfocused window. This should force the pending key to get dropped.
5156 NotifyMotionArgs motionArgs =
5157 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5158 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5159 mDispatcher->notifyMotion(&motionArgs);
5160
5161 // We do not consume the motion right away, because that would require dispatcher to first
5162 // process (== drop) the key event, and by that time, ANR will be raised.
5163 // Set the focused window first.
5164 mFocusedWindow->setFocusable(true);
5165 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5166 setFocusedWindow(mFocusedWindow);
5167 mFocusedWindow->consumeFocusEvent(true);
5168 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5169 // to another application. This could be a bug / behaviour in the policy.
5170
5171 mUnfocusedWindow->consumeMotionDown();
5172
5173 ASSERT_TRUE(mDispatcher->waitForIdle());
5174 // Should not ANR because we actually have a focused window. It was just added too slowly.
5175 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5176}
5177
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005178// These tests ensure we cannot send touch events to a window that's positioned behind a window
5179// that has feature NO_INPUT_CHANNEL.
5180// Layout:
5181// Top (closest to user)
5182// mNoInputWindow (above all windows)
5183// mBottomWindow
5184// Bottom (furthest from user)
5185class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5186 virtual void SetUp() override {
5187 InputDispatcherTest::SetUp();
5188
5189 mApplication = std::make_shared<FakeApplicationHandle>();
5190 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5191 "Window without input channel", ADISPLAY_ID_DEFAULT,
5192 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5193
chaviw3277faf2021-05-19 16:45:23 -05005194 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005195 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5196 // It's perfectly valid for this window to not have an associated input channel
5197
5198 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5199 ADISPLAY_ID_DEFAULT);
5200 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5201
5202 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5203 }
5204
5205protected:
5206 std::shared_ptr<FakeApplicationHandle> mApplication;
5207 sp<FakeWindowHandle> mNoInputWindow;
5208 sp<FakeWindowHandle> mBottomWindow;
5209};
5210
5211TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5212 PointF touchedPoint = {10, 10};
5213
5214 NotifyMotionArgs motionArgs =
5215 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5216 ADISPLAY_ID_DEFAULT, {touchedPoint});
5217 mDispatcher->notifyMotion(&motionArgs);
5218
5219 mNoInputWindow->assertNoEvents();
5220 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5221 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5222 // and therefore should prevent mBottomWindow from receiving touches
5223 mBottomWindow->assertNoEvents();
5224}
5225
5226/**
5227 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5228 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5229 */
5230TEST_F(InputDispatcherMultiWindowOcclusionTests,
5231 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5232 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5233 "Window with input channel and NO_INPUT_CHANNEL",
5234 ADISPLAY_ID_DEFAULT);
5235
chaviw3277faf2021-05-19 16:45:23 -05005236 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005237 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5238 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5239
5240 PointF touchedPoint = {10, 10};
5241
5242 NotifyMotionArgs motionArgs =
5243 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5244 ADISPLAY_ID_DEFAULT, {touchedPoint});
5245 mDispatcher->notifyMotion(&motionArgs);
5246
5247 mNoInputWindow->assertNoEvents();
5248 mBottomWindow->assertNoEvents();
5249}
5250
Vishnu Nair958da932020-08-21 17:12:37 -07005251class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5252protected:
5253 std::shared_ptr<FakeApplicationHandle> mApp;
5254 sp<FakeWindowHandle> mWindow;
5255 sp<FakeWindowHandle> mMirror;
5256
5257 virtual void SetUp() override {
5258 InputDispatcherTest::SetUp();
5259 mApp = std::make_shared<FakeApplicationHandle>();
5260 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5261 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5262 mWindow->getToken());
5263 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5264 mWindow->setFocusable(true);
5265 mMirror->setFocusable(true);
5266 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5267 }
5268};
5269
5270TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5271 // Request focus on a mirrored window
5272 setFocusedWindow(mMirror);
5273
5274 // window gets focused
5275 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005276 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5277 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005278 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5279}
5280
5281// A focused & mirrored window remains focused only if the window and its mirror are both
5282// focusable.
5283TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5284 setFocusedWindow(mMirror);
5285
5286 // window gets focused
5287 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005288 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5289 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005290 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005291 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5292 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005293 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5294
5295 mMirror->setFocusable(false);
5296 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5297
5298 // window loses focus since one of the windows associated with the token in not focusable
5299 mWindow->consumeFocusEvent(false);
5300
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005301 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5302 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005303 mWindow->assertNoEvents();
5304}
5305
5306// A focused & mirrored window remains focused until the window and its mirror both become
5307// invisible.
5308TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5309 setFocusedWindow(mMirror);
5310
5311 // window gets focused
5312 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005313 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5314 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005315 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005316 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5317 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005318 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5319
5320 mMirror->setVisible(false);
5321 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5322
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005323 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5324 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005325 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005326 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5327 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005328 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5329
5330 mWindow->setVisible(false);
5331 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5332
5333 // window loses focus only after all windows associated with the token become invisible.
5334 mWindow->consumeFocusEvent(false);
5335
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005336 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5337 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005338 mWindow->assertNoEvents();
5339}
5340
5341// A focused & mirrored window remains focused until both windows are removed.
5342TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5343 setFocusedWindow(mMirror);
5344
5345 // window gets focused
5346 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005347 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5348 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005349 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005350 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5351 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005352 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5353
5354 // single window is removed but the window token remains focused
5355 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5356
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005357 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5358 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005359 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005360 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5361 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005362 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5363
5364 // Both windows are removed
5365 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5366 mWindow->consumeFocusEvent(false);
5367
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005368 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5369 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005370 mWindow->assertNoEvents();
5371}
5372
5373// Focus request can be pending until one window becomes visible.
5374TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5375 // Request focus on an invisible mirror.
5376 mWindow->setVisible(false);
5377 mMirror->setVisible(false);
5378 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5379 setFocusedWindow(mMirror);
5380
5381 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005382 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005383 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005384 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005385
5386 mMirror->setVisible(true);
5387 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5388
5389 // window gets focused
5390 mWindow->consumeFocusEvent(true);
5391 // window gets the pending key event
5392 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5393}
Prabir Pradhan99987712020-11-10 18:43:05 -08005394
5395class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5396protected:
5397 std::shared_ptr<FakeApplicationHandle> mApp;
5398 sp<FakeWindowHandle> mWindow;
5399 sp<FakeWindowHandle> mSecondWindow;
5400
5401 void SetUp() override {
5402 InputDispatcherTest::SetUp();
5403 mApp = std::make_shared<FakeApplicationHandle>();
5404 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5405 mWindow->setFocusable(true);
5406 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5407 mSecondWindow->setFocusable(true);
5408
5409 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5410 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5411
5412 setFocusedWindow(mWindow);
5413 mWindow->consumeFocusEvent(true);
5414 }
5415
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005416 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5417 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005418 mDispatcher->notifyPointerCaptureChanged(&args);
5419 }
5420
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005421 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5422 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005423 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005424 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5425 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005426 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005427 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005428 }
5429};
5430
5431TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5432 // Ensure that capture cannot be obtained for unfocused windows.
5433 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5434 mFakePolicy->assertSetPointerCaptureNotCalled();
5435 mSecondWindow->assertNoEvents();
5436
5437 // Ensure that capture can be enabled from the focus window.
5438 requestAndVerifyPointerCapture(mWindow, true);
5439
5440 // Ensure that capture cannot be disabled from a window that does not have capture.
5441 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5442 mFakePolicy->assertSetPointerCaptureNotCalled();
5443
5444 // Ensure that capture can be disabled from the window with capture.
5445 requestAndVerifyPointerCapture(mWindow, false);
5446}
5447
5448TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005449 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005450
5451 setFocusedWindow(mSecondWindow);
5452
5453 // Ensure that the capture disabled event was sent first.
5454 mWindow->consumeCaptureEvent(false);
5455 mWindow->consumeFocusEvent(false);
5456 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005457 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005458
5459 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005460 notifyPointerCaptureChanged({});
5461 notifyPointerCaptureChanged(request);
5462 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005463 mWindow->assertNoEvents();
5464 mSecondWindow->assertNoEvents();
5465 mFakePolicy->assertSetPointerCaptureNotCalled();
5466}
5467
5468TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005469 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005470
5471 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005472 notifyPointerCaptureChanged({});
5473 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005474
5475 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005476 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005477 mWindow->consumeCaptureEvent(false);
5478 mWindow->assertNoEvents();
5479}
5480
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005481TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5482 requestAndVerifyPointerCapture(mWindow, true);
5483
5484 // The first window loses focus.
5485 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005486 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005487 mWindow->consumeCaptureEvent(false);
5488
5489 // Request Pointer Capture from the second window before the notification from InputReader
5490 // arrives.
5491 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005492 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005493
5494 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005495 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005496
5497 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005498 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005499
5500 mSecondWindow->consumeFocusEvent(true);
5501 mSecondWindow->consumeCaptureEvent(true);
5502}
5503
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005504TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5505 // App repeatedly enables and disables capture.
5506 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5507 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5508 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5509 mFakePolicy->assertSetPointerCaptureCalled(false);
5510 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5511 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5512
5513 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5514 // first request is now stale, this should do nothing.
5515 notifyPointerCaptureChanged(firstRequest);
5516 mWindow->assertNoEvents();
5517
5518 // InputReader notifies that the second request was enabled.
5519 notifyPointerCaptureChanged(secondRequest);
5520 mWindow->consumeCaptureEvent(true);
5521}
5522
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005523class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5524protected:
5525 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005526
5527 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5528 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5529
5530 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5531 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5532
5533 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5534 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5535 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5536 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5537 MAXIMUM_OBSCURING_OPACITY);
5538
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005539 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005540 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005541 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005542
5543 sp<FakeWindowHandle> mTouchWindow;
5544
5545 virtual void SetUp() override {
5546 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005547 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005548 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5549 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5550 }
5551
5552 virtual void TearDown() override {
5553 InputDispatcherTest::TearDown();
5554 mTouchWindow.clear();
5555 }
5556
chaviw3277faf2021-05-19 16:45:23 -05005557 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5558 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005559 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005560 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005561 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005562 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005563 return window;
5564 }
5565
5566 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5567 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5568 sp<FakeWindowHandle> window =
5569 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5570 // Generate an arbitrary PID based on the UID
5571 window->setOwnerInfo(1777 + (uid % 10000), uid);
5572 return window;
5573 }
5574
5575 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5576 NotifyMotionArgs args =
5577 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5578 ADISPLAY_ID_DEFAULT, points);
5579 mDispatcher->notifyMotion(&args);
5580 }
5581};
5582
5583TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005584 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005585 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005586 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005587
5588 touch();
5589
5590 mTouchWindow->assertNoEvents();
5591}
5592
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005593TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005594 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5595 const sp<FakeWindowHandle>& w =
5596 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5597 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5598
5599 touch();
5600
5601 mTouchWindow->assertNoEvents();
5602}
5603
5604TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005605 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5606 const sp<FakeWindowHandle>& w =
5607 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5608 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5609
5610 touch();
5611
5612 w->assertNoEvents();
5613}
5614
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005615TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005616 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5617 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005618
5619 touch();
5620
5621 mTouchWindow->consumeAnyMotionDown();
5622}
5623
5624TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005625 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005626 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005627 w->setFrame(Rect(0, 0, 50, 50));
5628 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005629
5630 touch({PointF{100, 100}});
5631
5632 mTouchWindow->consumeAnyMotionDown();
5633}
5634
5635TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005636 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005637 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005638 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5639
5640 touch();
5641
5642 mTouchWindow->consumeAnyMotionDown();
5643}
5644
5645TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5646 const sp<FakeWindowHandle>& w =
5647 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5648 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005649
5650 touch();
5651
5652 mTouchWindow->consumeAnyMotionDown();
5653}
5654
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005655TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5656 const sp<FakeWindowHandle>& w =
5657 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5658 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5659
5660 touch();
5661
5662 w->assertNoEvents();
5663}
5664
5665/**
5666 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5667 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5668 * window, the occluding window will still receive ACTION_OUTSIDE event.
5669 */
5670TEST_F(InputDispatcherUntrustedTouchesTest,
5671 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5672 const sp<FakeWindowHandle>& w =
5673 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005674 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005675 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5676
5677 touch();
5678
5679 w->consumeMotionOutside();
5680}
5681
5682TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5683 const sp<FakeWindowHandle>& w =
5684 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005685 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005686 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5687
5688 touch();
5689
5690 InputEvent* event = w->consume();
5691 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5692 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5693 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5694 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5695}
5696
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005697TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005698 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005699 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5700 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005701 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5702
5703 touch();
5704
5705 mTouchWindow->consumeAnyMotionDown();
5706}
5707
5708TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5709 const sp<FakeWindowHandle>& w =
5710 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5711 MAXIMUM_OBSCURING_OPACITY);
5712 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005713
5714 touch();
5715
5716 mTouchWindow->consumeAnyMotionDown();
5717}
5718
5719TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005720 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005721 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5722 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005723 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5724
5725 touch();
5726
5727 mTouchWindow->assertNoEvents();
5728}
5729
5730TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5731 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5732 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005733 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5734 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005735 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005736 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5737 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005738 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5739
5740 touch();
5741
5742 mTouchWindow->assertNoEvents();
5743}
5744
5745TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5746 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5747 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005748 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5749 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005750 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005751 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5752 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005753 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5754
5755 touch();
5756
5757 mTouchWindow->consumeAnyMotionDown();
5758}
5759
5760TEST_F(InputDispatcherUntrustedTouchesTest,
5761 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5762 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005763 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5764 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005765 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005766 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5767 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005768 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5769
5770 touch();
5771
5772 mTouchWindow->consumeAnyMotionDown();
5773}
5774
5775TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5776 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005777 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5778 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005779 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005780 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5781 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005782 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005783
5784 touch();
5785
5786 mTouchWindow->assertNoEvents();
5787}
5788
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005789TEST_F(InputDispatcherUntrustedTouchesTest,
5790 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5791 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005792 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5793 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005794 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005795 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5796 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005797 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5798
5799 touch();
5800
5801 mTouchWindow->assertNoEvents();
5802}
5803
5804TEST_F(InputDispatcherUntrustedTouchesTest,
5805 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5806 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005807 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5808 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005809 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005810 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5811 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005812 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5813
5814 touch();
5815
5816 mTouchWindow->consumeAnyMotionDown();
5817}
5818
5819TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5820 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005821 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5822 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005823 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5824
5825 touch();
5826
5827 mTouchWindow->consumeAnyMotionDown();
5828}
5829
5830TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5831 const sp<FakeWindowHandle>& w =
5832 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5833 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5834
5835 touch();
5836
5837 mTouchWindow->consumeAnyMotionDown();
5838}
5839
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005840TEST_F(InputDispatcherUntrustedTouchesTest,
5841 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5842 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5843 const sp<FakeWindowHandle>& w =
5844 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5845 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5846
5847 touch();
5848
5849 mTouchWindow->assertNoEvents();
5850}
5851
5852TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5853 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5854 const sp<FakeWindowHandle>& w =
5855 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5856 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5857
5858 touch();
5859
5860 mTouchWindow->consumeAnyMotionDown();
5861}
5862
5863TEST_F(InputDispatcherUntrustedTouchesTest,
5864 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5865 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5866 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005867 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5868 OPACITY_ABOVE_THRESHOLD);
5869 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5870
5871 touch();
5872
5873 mTouchWindow->consumeAnyMotionDown();
5874}
5875
5876TEST_F(InputDispatcherUntrustedTouchesTest,
5877 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5878 const sp<FakeWindowHandle>& w1 =
5879 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5880 OPACITY_BELOW_THRESHOLD);
5881 const sp<FakeWindowHandle>& w2 =
5882 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5883 OPACITY_BELOW_THRESHOLD);
5884 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5885
5886 touch();
5887
5888 mTouchWindow->assertNoEvents();
5889}
5890
5891/**
5892 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5893 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5894 * (which alone would result in allowing touches) does not affect the blocking behavior.
5895 */
5896TEST_F(InputDispatcherUntrustedTouchesTest,
5897 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5898 const sp<FakeWindowHandle>& wB =
5899 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5900 OPACITY_BELOW_THRESHOLD);
5901 const sp<FakeWindowHandle>& wC =
5902 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5903 OPACITY_BELOW_THRESHOLD);
5904 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5905
5906 touch();
5907
5908 mTouchWindow->assertNoEvents();
5909}
5910
5911/**
5912 * This test is testing that a window from a different UID but with same application token doesn't
5913 * block the touch. Apps can share the application token for close UI collaboration for example.
5914 */
5915TEST_F(InputDispatcherUntrustedTouchesTest,
5916 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5917 const sp<FakeWindowHandle>& w =
5918 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5919 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005920 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5921
5922 touch();
5923
5924 mTouchWindow->consumeAnyMotionDown();
5925}
5926
arthurhungb89ccb02020-12-30 16:19:01 +08005927class InputDispatcherDragTests : public InputDispatcherTest {
5928protected:
5929 std::shared_ptr<FakeApplicationHandle> mApp;
5930 sp<FakeWindowHandle> mWindow;
5931 sp<FakeWindowHandle> mSecondWindow;
5932 sp<FakeWindowHandle> mDragWindow;
5933
5934 void SetUp() override {
5935 InputDispatcherTest::SetUp();
5936 mApp = std::make_shared<FakeApplicationHandle>();
5937 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5938 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005939 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005940
5941 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5942 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005943 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005944
5945 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5946 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5947 }
5948
5949 // Start performing drag, we will create a drag window and transfer touch to it.
5950 void performDrag() {
5951 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5952 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5953 {50, 50}))
5954 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5955
5956 // Window should receive motion event.
5957 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5958
5959 // The drag window covers the entire display
5960 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5961 mDispatcher->setInputWindows(
5962 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5963
5964 // Transfer touch focus to the drag window
5965 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5966 true /* isDragDrop */);
5967 mWindow->consumeMotionCancel();
5968 mDragWindow->consumeMotionDown();
5969 }
arthurhung6d4bed92021-03-17 11:59:33 +08005970
5971 // Start performing drag, we will create a drag window and transfer touch to it.
5972 void performStylusDrag() {
5973 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5974 injectMotionEvent(mDispatcher,
5975 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5976 AINPUT_SOURCE_STYLUS)
5977 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5978 .pointer(PointerBuilder(0,
5979 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5980 .x(50)
5981 .y(50))
5982 .build()));
5983 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5984
5985 // The drag window covers the entire display
5986 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5987 mDispatcher->setInputWindows(
5988 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5989
5990 // Transfer touch focus to the drag window
5991 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5992 true /* isDragDrop */);
5993 mWindow->consumeMotionCancel();
5994 mDragWindow->consumeMotionDown();
5995 }
arthurhungb89ccb02020-12-30 16:19:01 +08005996};
5997
5998TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5999 performDrag();
6000
6001 // Move on window.
6002 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6003 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6004 ADISPLAY_ID_DEFAULT, {50, 50}))
6005 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6006 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6007 mWindow->consumeDragEvent(false, 50, 50);
6008 mSecondWindow->assertNoEvents();
6009
6010 // Move to another window.
6011 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6012 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6013 ADISPLAY_ID_DEFAULT, {150, 50}))
6014 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6015 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6016 mWindow->consumeDragEvent(true, 150, 50);
6017 mSecondWindow->consumeDragEvent(false, 50, 50);
6018
6019 // Move back to original window.
6020 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6021 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6022 ADISPLAY_ID_DEFAULT, {50, 50}))
6023 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6024 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6025 mWindow->consumeDragEvent(false, 50, 50);
6026 mSecondWindow->consumeDragEvent(true, -50, 50);
6027
6028 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6029 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6030 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6031 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6032 mWindow->assertNoEvents();
6033 mSecondWindow->assertNoEvents();
6034}
6035
arthurhungf452d0b2021-01-06 00:19:52 +08006036TEST_F(InputDispatcherDragTests, DragAndDrop) {
6037 performDrag();
6038
6039 // Move on window.
6040 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6041 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6042 ADISPLAY_ID_DEFAULT, {50, 50}))
6043 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6044 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6045 mWindow->consumeDragEvent(false, 50, 50);
6046 mSecondWindow->assertNoEvents();
6047
6048 // Move to another window.
6049 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6050 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6051 ADISPLAY_ID_DEFAULT, {150, 50}))
6052 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6053 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6054 mWindow->consumeDragEvent(true, 150, 50);
6055 mSecondWindow->consumeDragEvent(false, 50, 50);
6056
6057 // drop to another window.
6058 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6059 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6060 {150, 50}))
6061 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6062 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6063 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6064 mWindow->assertNoEvents();
6065 mSecondWindow->assertNoEvents();
6066}
6067
arthurhung6d4bed92021-03-17 11:59:33 +08006068TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6069 performStylusDrag();
6070
6071 // Move on window and keep button pressed.
6072 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6073 injectMotionEvent(mDispatcher,
6074 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6075 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6076 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6077 .x(50)
6078 .y(50))
6079 .build()))
6080 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6081 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6082 mWindow->consumeDragEvent(false, 50, 50);
6083 mSecondWindow->assertNoEvents();
6084
6085 // Move to another window and release button, expect to drop item.
6086 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6087 injectMotionEvent(mDispatcher,
6088 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6089 .buttonState(0)
6090 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6091 .x(150)
6092 .y(50))
6093 .build()))
6094 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6095 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6096 mWindow->assertNoEvents();
6097 mSecondWindow->assertNoEvents();
6098 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6099
6100 // nothing to the window.
6101 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6102 injectMotionEvent(mDispatcher,
6103 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6104 .buttonState(0)
6105 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6106 .x(150)
6107 .y(50))
6108 .build()))
6109 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6110 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6111 mWindow->assertNoEvents();
6112 mSecondWindow->assertNoEvents();
6113}
6114
Arthur Hung6d0571e2021-04-09 20:18:16 +08006115TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6116 performDrag();
6117
6118 // Set second window invisible.
6119 mSecondWindow->setVisible(false);
6120 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6121
6122 // Move on window.
6123 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6124 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6125 ADISPLAY_ID_DEFAULT, {50, 50}))
6126 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6127 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6128 mWindow->consumeDragEvent(false, 50, 50);
6129 mSecondWindow->assertNoEvents();
6130
6131 // Move to another window.
6132 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6133 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6134 ADISPLAY_ID_DEFAULT, {150, 50}))
6135 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6136 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6137 mWindow->consumeDragEvent(true, 150, 50);
6138 mSecondWindow->assertNoEvents();
6139
6140 // drop to another window.
6141 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6142 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6143 {150, 50}))
6144 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6145 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6146 mFakePolicy->assertDropTargetEquals(nullptr);
6147 mWindow->assertNoEvents();
6148 mSecondWindow->assertNoEvents();
6149}
6150
Vishnu Nair062a8672021-09-03 16:07:44 -07006151class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6152
6153TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6154 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6155 sp<FakeWindowHandle> window =
6156 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6157 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
6158 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6159 window->setFocusable(true);
6160 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6161 setFocusedWindow(window);
6162 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6163
6164 // With the flag set, window should not get any input
6165 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6166 mDispatcher->notifyKey(&keyArgs);
6167 window->assertNoEvents();
6168
6169 NotifyMotionArgs motionArgs =
6170 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6171 ADISPLAY_ID_DEFAULT);
6172 mDispatcher->notifyMotion(&motionArgs);
6173 window->assertNoEvents();
6174
6175 // With the flag cleared, the window should get input
6176 window->setInputFeatures({});
6177 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6178
6179 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6180 mDispatcher->notifyKey(&keyArgs);
6181 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6182
6183 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6184 ADISPLAY_ID_DEFAULT);
6185 mDispatcher->notifyMotion(&motionArgs);
6186 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6187 window->assertNoEvents();
6188}
6189
6190TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6191 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6192 std::make_shared<FakeApplicationHandle>();
6193 sp<FakeWindowHandle> obscuringWindow =
6194 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6195 ADISPLAY_ID_DEFAULT);
6196 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6197 obscuringWindow->setOwnerInfo(111, 111);
6198 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6199 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6200 sp<FakeWindowHandle> window =
6201 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6202 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6203 window->setOwnerInfo(222, 222);
6204 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6205 window->setFocusable(true);
6206 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6207 setFocusedWindow(window);
6208 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6209
6210 // With the flag set, window should not get any input
6211 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6212 mDispatcher->notifyKey(&keyArgs);
6213 window->assertNoEvents();
6214
6215 NotifyMotionArgs motionArgs =
6216 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6217 ADISPLAY_ID_DEFAULT);
6218 mDispatcher->notifyMotion(&motionArgs);
6219 window->assertNoEvents();
6220
6221 // With the flag cleared, the window should get input
6222 window->setInputFeatures({});
6223 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6224
6225 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6226 mDispatcher->notifyKey(&keyArgs);
6227 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6228
6229 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6230 ADISPLAY_ID_DEFAULT);
6231 mDispatcher->notifyMotion(&motionArgs);
6232 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6233 window->assertNoEvents();
6234}
6235
6236TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6237 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6238 std::make_shared<FakeApplicationHandle>();
6239 sp<FakeWindowHandle> obscuringWindow =
6240 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6241 ADISPLAY_ID_DEFAULT);
6242 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6243 obscuringWindow->setOwnerInfo(111, 111);
6244 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6245 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6246 sp<FakeWindowHandle> window =
6247 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6248 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6249 window->setOwnerInfo(222, 222);
6250 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6251 window->setFocusable(true);
6252 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6253 setFocusedWindow(window);
6254 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6255
6256 // With the flag set, window should not get any input
6257 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6258 mDispatcher->notifyKey(&keyArgs);
6259 window->assertNoEvents();
6260
6261 NotifyMotionArgs motionArgs =
6262 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6263 ADISPLAY_ID_DEFAULT);
6264 mDispatcher->notifyMotion(&motionArgs);
6265 window->assertNoEvents();
6266
6267 // When the window is no longer obscured because it went on top, it should get input
6268 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6269
6270 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6271 mDispatcher->notifyKey(&keyArgs);
6272 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6273
6274 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6275 ADISPLAY_ID_DEFAULT);
6276 mDispatcher->notifyMotion(&motionArgs);
6277 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6278 window->assertNoEvents();
6279}
6280
Antonio Kantekf16f2832021-09-28 04:39:20 +00006281class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6282protected:
6283 std::shared_ptr<FakeApplicationHandle> mApp;
6284 sp<FakeWindowHandle> mWindow;
6285 sp<FakeWindowHandle> mSecondWindow;
6286
6287 void SetUp() override {
6288 InputDispatcherTest::SetUp();
6289
6290 mApp = std::make_shared<FakeApplicationHandle>();
6291 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6292 mWindow->setFocusable(true);
6293 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6294 mSecondWindow->setFocusable(true);
6295
6296 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6297 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6298
6299 setFocusedWindow(mWindow);
6300 mWindow->consumeFocusEvent(true);
6301 }
6302
6303 void changeAndVerifyTouchMode(bool inTouchMode) {
6304 mDispatcher->setInTouchMode(inTouchMode);
6305 mWindow->consumeTouchModeEvent(inTouchMode);
6306 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6307 }
6308};
6309
6310TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
6311 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode);
6312}
6313
6314TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
6315 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode);
6316 mWindow->assertNoEvents();
6317 mSecondWindow->assertNoEvents();
6318}
6319
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006320class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6321public:
6322 sp<FakeWindowHandle> createSpy(const Flags<WindowInfo::Flag> flags) {
6323 std::shared_ptr<FakeApplicationHandle> application =
6324 std::make_shared<FakeApplicationHandle>();
6325 std::string name = "Fake Spy ";
6326 name += std::to_string(mSpyCount++);
6327 sp<FakeWindowHandle> spy =
6328 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
6329 spy->setInputFeatures(WindowInfo::Feature::SPY);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006330 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006331 spy->addFlags(flags);
6332 return spy;
6333 }
6334
6335 sp<FakeWindowHandle> createForeground() {
6336 std::shared_ptr<FakeApplicationHandle> application =
6337 std::make_shared<FakeApplicationHandle>();
6338 sp<FakeWindowHandle> window =
6339 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
6340 window->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
6341 return window;
6342 }
6343
6344private:
6345 int mSpyCount{0};
6346};
6347
6348/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006349 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6350 */
6351TEST_F(InputDispatcherSpyWindowTest, UntrustedSpy_AbortsDispatcher) {
6352 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6353 spy->setTrustedOverlay(false);
6354 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6355 ".* not a trusted overlay");
6356}
6357
6358/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006359 * Input injection into a display with a spy window but no foreground windows should succeed.
6360 */
6361TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
6362 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6363 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6364
6365 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6366 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6367 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6368 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6369}
6370
6371/**
6372 * Verify the order in which different input windows receive events. The touched foreground window
6373 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6374 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6375 * receive events before ones belows it.
6376 *
6377 * Here, we set up a scenario with four windows in the following Z order from the top:
6378 * spy1, spy2, window, spy3.
6379 * We then inject an event and verify that the foreground "window" receives it first, followed by
6380 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6381 * window.
6382 */
6383TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6384 auto window = createForeground();
6385 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6386 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6387 auto spy3 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6388 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6389 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6390 const size_t numChannels = channels.size();
6391
6392 base::unique_fd epollFd(epoll_create1(0 /*flags*/));
6393 if (!epollFd.ok()) {
6394 FAIL() << "Failed to create epoll fd";
6395 }
6396
6397 for (size_t i = 0; i < numChannels; i++) {
6398 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6399 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6400 FAIL() << "Failed to add fd to epoll";
6401 }
6402 }
6403
6404 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6405 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6406 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6407
6408 std::vector<size_t> eventOrder;
6409 std::vector<struct epoll_event> events(numChannels);
6410 for (;;) {
6411 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6412 (100ms).count());
6413 if (nFds < 0) {
6414 FAIL() << "Failed to call epoll_wait";
6415 }
6416 if (nFds == 0) {
6417 break; // epoll_wait timed out
6418 }
6419 for (int i = 0; i < nFds; i++) {
6420 ASSERT_EQ(EPOLLIN, events[i].events);
6421 eventOrder.push_back(events[i].data.u64);
6422 channels[i]->consumeMotionDown();
6423 }
6424 }
6425
6426 // Verify the order in which the events were received.
6427 EXPECT_EQ(3u, eventOrder.size());
6428 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6429 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6430 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6431}
6432
6433/**
6434 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6435 */
6436TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6437 auto window = createForeground();
6438 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCHABLE);
6439 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6440
6441 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6442 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6443 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6444 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6445 spy->assertNoEvents();
6446}
6447
6448/**
6449 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6450 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6451 * to the window.
6452 */
6453TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6454 auto window = createForeground();
6455 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6456 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6457 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6458
6459 // Inject an event outside the spy window's touchable region.
6460 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6461 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6462 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6463 window->consumeMotionDown();
6464 spy->assertNoEvents();
6465 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6466 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6467 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6468 window->consumeMotionUp();
6469 spy->assertNoEvents();
6470
6471 // Inject an event inside the spy window's touchable region.
6472 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6473 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6474 {5, 10}))
6475 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6476 window->consumeMotionDown();
6477 spy->consumeMotionDown();
6478}
6479
6480/**
6481 * A spy window that is a modal window will receive gestures outside of its frame and touchable
6482 * region.
6483 */
6484TEST_F(InputDispatcherSpyWindowTest, ModalWindow) {
6485 auto window = createForeground();
6486 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6487 // This spy window does not have the NOT_TOUCH_MODAL flag set.
6488 spy->setFrame(Rect{0, 0, 20, 20});
6489 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6490
6491 // Inject an event outside the spy window's frame and touchable region.
6492 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6493 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6494 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6495 window->consumeMotionDown();
6496 spy->consumeMotionDown();
6497}
6498
6499/**
6500 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
6501 * flag.
6502 */
6503TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6504 auto window = createForeground();
6505 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
6506 spy->setFrame(Rect{0, 0, 20, 20});
6507 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6508
6509 // Inject an event outside the spy window's frame and touchable region.
6510 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6511 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6512 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6513 window->consumeMotionDown();
6514 spy->consumeMotionOutside();
6515}
6516
6517/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006518 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6519 * any other windows - including other spy windows - will also be cancelled.
6520 */
6521TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6522 auto window = createForeground();
6523 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6524 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6525 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6526
6527 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6528 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6529 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6530 window->consumeMotionDown();
6531 spy1->consumeMotionDown();
6532 spy2->consumeMotionDown();
6533
6534 // Pilfer pointers from the second spy window.
6535 mDispatcher->pilferPointers(spy2->getToken());
6536 spy2->assertNoEvents();
6537 spy1->consumeMotionCancel();
6538 window->consumeMotionCancel();
6539
6540 // The rest of the gesture should only be sent to the second spy window.
6541 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6542 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6543 ADISPLAY_ID_DEFAULT))
6544 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6545 spy2->consumeMotionMove();
6546 spy1->assertNoEvents();
6547 window->assertNoEvents();
6548}
6549
6550/**
6551 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6552 * pointers that are down within its bounds.
6553 */
6554TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6555 auto windowLeft = createForeground();
6556 windowLeft->setFrame({0, 0, 100, 200});
6557 auto windowRight = createForeground();
6558 windowRight->setFrame({100, 0, 200, 200});
6559 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6560 spy->setFrame({0, 0, 200, 200});
6561 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6562
6563 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6564 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6565 {50, 50}))
6566 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6567 windowLeft->consumeMotionDown();
6568 spy->consumeMotionDown();
6569
6570 const MotionEvent secondFingerDownEvent =
6571 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6572 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6573 AINPUT_SOURCE_TOUCHSCREEN)
6574 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6575 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6576 .pointer(
6577 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6578 .build();
6579 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6580 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6581 InputEventInjectionSync::WAIT_FOR_RESULT))
6582 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6583 windowRight->consumeMotionDown();
6584 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6585}
6586
6587/**
6588 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6589 * the spy should receive the second pointer with ACTION_DOWN.
6590 */
6591TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6592 auto window = createForeground();
6593 window->setFrame({0, 0, 200, 200});
6594 auto spyRight = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6595 spyRight->setFrame({100, 0, 200, 200});
6596 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6597
6598 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6599 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6600 {50, 50}))
6601 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6602 window->consumeMotionDown();
6603 spyRight->assertNoEvents();
6604
6605 const MotionEvent secondFingerDownEvent =
6606 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6607 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6608 AINPUT_SOURCE_TOUCHSCREEN)
6609 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6610 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6611 .pointer(
6612 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6613 .build();
6614 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6615 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6616 InputEventInjectionSync::WAIT_FOR_RESULT))
6617 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6618 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6619 spyRight->consumeMotionDown();
6620}
6621
Prabir Pradhand65552b2021-10-07 11:23:50 -07006622class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6623public:
6624 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6625 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6626 std::make_shared<FakeApplicationHandle>();
6627 sp<FakeWindowHandle> overlay =
6628 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6629 ADISPLAY_ID_DEFAULT);
6630 overlay->setFocusable(false);
6631 overlay->setOwnerInfo(111, 111);
6632 overlay->setFlags(WindowInfo::Flag::NOT_TOUCHABLE | WindowInfo::Flag::SPLIT_TOUCH);
6633 overlay->setInputFeatures(WindowInfo::Feature::INTERCEPTS_STYLUS);
6634 overlay->setTrustedOverlay(true);
6635
6636 std::shared_ptr<FakeApplicationHandle> application =
6637 std::make_shared<FakeApplicationHandle>();
6638 sp<FakeWindowHandle> window =
6639 new FakeWindowHandle(application, mDispatcher, "Application window",
6640 ADISPLAY_ID_DEFAULT);
6641 window->setFocusable(true);
6642 window->setOwnerInfo(222, 222);
6643 window->setFlags(WindowInfo::Flag::SPLIT_TOUCH);
6644
6645 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6646 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6647 setFocusedWindow(window);
6648 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6649 return {std::move(overlay), std::move(window)};
6650 }
6651
6652 void sendFingerEvent(int32_t action) {
6653 NotifyMotionArgs motionArgs =
6654 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6655 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6656 mDispatcher->notifyMotion(&motionArgs);
6657 }
6658
6659 void sendStylusEvent(int32_t action) {
6660 NotifyMotionArgs motionArgs =
6661 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6662 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6663 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6664 mDispatcher->notifyMotion(&motionArgs);
6665 }
6666};
6667
6668TEST_F(InputDispatcherStylusInterceptorTest, UntrustedOverlay_AbortsDispatcher) {
6669 auto [overlay, window] = setupStylusOverlayScenario();
6670 overlay->setTrustedOverlay(false);
6671 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6672 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6673 ".* not a trusted overlay");
6674}
6675
6676TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6677 auto [overlay, window] = setupStylusOverlayScenario();
6678 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6679
6680 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6681 overlay->consumeMotionDown();
6682 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6683 overlay->consumeMotionUp();
6684
6685 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6686 window->consumeMotionDown();
6687 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6688 window->consumeMotionUp();
6689
6690 overlay->assertNoEvents();
6691 window->assertNoEvents();
6692}
6693
6694TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6695 auto [overlay, window] = setupStylusOverlayScenario();
6696 overlay->setInputFeatures(overlay->getInfo()->inputFeatures | WindowInfo::Feature::SPY);
6697 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6698
6699 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6700 overlay->consumeMotionDown();
6701 window->consumeMotionDown();
6702 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6703 overlay->consumeMotionUp();
6704 window->consumeMotionUp();
6705
6706 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6707 window->consumeMotionDown();
6708 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6709 window->consumeMotionUp();
6710
6711 overlay->assertNoEvents();
6712 window->assertNoEvents();
6713}
6714
Garfield Tane84e6f92019-08-29 17:28:41 -07006715} // namespace android::inputdispatcher