blob: e2f0343513fdc88d06a9377c877a62dd5d199696 [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
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001129 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1130 int32_t expectedFlags = 0) {
1131 InputEvent* event = consume();
1132 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1133 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1134 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1135 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1136 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1137 }
1138
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001139 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1140 ASSERT_NE(mInputReceiver, nullptr)
1141 << "Cannot consume events from a window with no receiver";
1142 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1143 }
1144
Prabir Pradhan99987712020-11-10 18:43:05 -08001145 void consumeCaptureEvent(bool hasCapture) {
1146 ASSERT_NE(mInputReceiver, nullptr)
1147 << "Cannot consume events from a window with no receiver";
1148 mInputReceiver->consumeCaptureEvent(hasCapture);
1149 }
1150
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001151 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1152 std::optional<int32_t> expectedDisplayId,
1153 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001154 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1155 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1156 expectedFlags);
1157 }
1158
arthurhungb89ccb02020-12-30 16:19:01 +08001159 void consumeDragEvent(bool isExiting, float x, float y) {
1160 mInputReceiver->consumeDragEvent(isExiting, x, y);
1161 }
1162
Antonio Kantekf16f2832021-09-28 04:39:20 +00001163 void consumeTouchModeEvent(bool inTouchMode) {
1164 ASSERT_NE(mInputReceiver, nullptr)
1165 << "Cannot consume events from a window with no receiver";
1166 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1167 }
1168
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001169 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001170 if (mInputReceiver == nullptr) {
1171 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1172 return std::nullopt;
1173 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001174 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001175 }
1176
1177 void finishEvent(uint32_t sequenceNum) {
1178 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1179 mInputReceiver->finishEvent(sequenceNum);
1180 }
1181
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001182 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1183 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1184 mInputReceiver->sendTimeline(inputEventId, timeline);
1185 }
1186
chaviwaf87b3e2019-10-01 16:59:28 -07001187 InputEvent* consume() {
1188 if (mInputReceiver == nullptr) {
1189 return nullptr;
1190 }
1191 return mInputReceiver->consume();
1192 }
1193
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001194 MotionEvent* consumeMotion() {
1195 InputEvent* event = consume();
1196 if (event == nullptr) {
1197 ADD_FAILURE() << "Consume failed : no event";
1198 return nullptr;
1199 }
1200 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1201 ADD_FAILURE() << "Instead of motion event, got "
1202 << inputEventTypeToString(event->getType());
1203 return nullptr;
1204 }
1205 return static_cast<MotionEvent*>(event);
1206 }
1207
Arthur Hungb92218b2018-08-14 12:00:21 +08001208 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001209 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001210 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001211 return; // Can't receive events if the window does not have input channel
1212 }
1213 ASSERT_NE(nullptr, mInputReceiver)
1214 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001215 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001216 }
1217
chaviwaf87b3e2019-10-01 16:59:28 -07001218 sp<IBinder> getToken() { return mInfo.token; }
1219
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001220 const std::string& getName() { return mName; }
1221
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001222 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1223 mInfo.ownerPid = ownerPid;
1224 mInfo.ownerUid = ownerUid;
1225 }
1226
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001227 void destroyReceiver() { mInputReceiver = nullptr; }
1228
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001229 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1230
chaviwd1c23182019-12-20 18:44:56 -08001231private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001232 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001233 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001234 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001235};
1236
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001237std::atomic<int32_t> FakeWindowHandle::sId{1};
1238
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001239static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001240 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001241 int32_t displayId = ADISPLAY_ID_NONE,
1242 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001243 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1244 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001245 KeyEvent event;
1246 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1247
1248 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001249 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001250 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1251 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001252
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001253 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1254 if (!allowKeyRepeat) {
1255 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1256 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001257 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001258 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001259 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001260}
1261
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001262static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001263 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001264 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1265}
1266
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001267// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1268// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1269// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001270static InputEventInjectionResult injectKeyDownNoRepeat(
1271 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001272 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1273 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1274 /* allowKeyRepeat */ false);
1275}
1276
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001277static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001278 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001279 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1280}
1281
Garfield Tandf26e862020-07-01 20:18:19 -07001282class PointerBuilder {
1283public:
1284 PointerBuilder(int32_t id, int32_t toolType) {
1285 mProperties.clear();
1286 mProperties.id = id;
1287 mProperties.toolType = toolType;
1288 mCoords.clear();
1289 }
1290
1291 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1292
1293 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1294
1295 PointerBuilder& axis(int32_t axis, float value) {
1296 mCoords.setAxisValue(axis, value);
1297 return *this;
1298 }
1299
1300 PointerProperties buildProperties() const { return mProperties; }
1301
1302 PointerCoords buildCoords() const { return mCoords; }
1303
1304private:
1305 PointerProperties mProperties;
1306 PointerCoords mCoords;
1307};
1308
1309class MotionEventBuilder {
1310public:
1311 MotionEventBuilder(int32_t action, int32_t source) {
1312 mAction = action;
1313 mSource = source;
1314 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1315 }
1316
1317 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1318 mEventTime = eventTime;
1319 return *this;
1320 }
1321
1322 MotionEventBuilder& displayId(int32_t displayId) {
1323 mDisplayId = displayId;
1324 return *this;
1325 }
1326
1327 MotionEventBuilder& actionButton(int32_t actionButton) {
1328 mActionButton = actionButton;
1329 return *this;
1330 }
1331
arthurhung6d4bed92021-03-17 11:59:33 +08001332 MotionEventBuilder& buttonState(int32_t buttonState) {
1333 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001334 return *this;
1335 }
1336
1337 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1338 mRawXCursorPosition = rawXCursorPosition;
1339 return *this;
1340 }
1341
1342 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1343 mRawYCursorPosition = rawYCursorPosition;
1344 return *this;
1345 }
1346
1347 MotionEventBuilder& pointer(PointerBuilder pointer) {
1348 mPointers.push_back(pointer);
1349 return *this;
1350 }
1351
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001352 MotionEventBuilder& addFlag(uint32_t flags) {
1353 mFlags |= flags;
1354 return *this;
1355 }
1356
Garfield Tandf26e862020-07-01 20:18:19 -07001357 MotionEvent build() {
1358 std::vector<PointerProperties> pointerProperties;
1359 std::vector<PointerCoords> pointerCoords;
1360 for (const PointerBuilder& pointer : mPointers) {
1361 pointerProperties.push_back(pointer.buildProperties());
1362 pointerCoords.push_back(pointer.buildCoords());
1363 }
1364
1365 // Set mouse cursor position for the most common cases to avoid boilerplate.
1366 if (mSource == AINPUT_SOURCE_MOUSE &&
1367 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1368 mPointers.size() == 1) {
1369 mRawXCursorPosition = pointerCoords[0].getX();
1370 mRawYCursorPosition = pointerCoords[0].getY();
1371 }
1372
1373 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001374 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001375 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001376 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001377 mButtonState, MotionClassification::NONE, identityTransform,
1378 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001379 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1380 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001381
1382 return event;
1383 }
1384
1385private:
1386 int32_t mAction;
1387 int32_t mSource;
1388 nsecs_t mEventTime;
1389 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1390 int32_t mActionButton{0};
1391 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001392 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001393 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1394 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1395
1396 std::vector<PointerBuilder> mPointers;
1397};
1398
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001399static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001400 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001401 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001402 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001403 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1404 injectionTimeout,
1405 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1406}
1407
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001408static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001409 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001410 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001411 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001412 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1413 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001414 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001415 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001416 MotionEvent event = MotionEventBuilder(action, source)
1417 .displayId(displayId)
1418 .eventTime(eventTime)
1419 .rawXCursorPosition(cursorPosition.x)
1420 .rawYCursorPosition(cursorPosition.y)
1421 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1422 .x(position.x)
1423 .y(position.y))
1424 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001425
1426 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001427 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001428}
1429
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001430static InputEventInjectionResult injectMotionDown(
1431 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1432 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001433 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001434}
1435
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001436static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001437 int32_t source, int32_t displayId,
1438 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001439 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001440}
1441
Jackal Guof9696682018-10-05 12:23:23 +08001442static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1443 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1444 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001445 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1446 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1447 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001448
1449 return args;
1450}
1451
chaviwd1c23182019-12-20 18:44:56 -08001452static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1453 const std::vector<PointF>& points) {
1454 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001455 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1456 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1457 }
1458
chaviwd1c23182019-12-20 18:44:56 -08001459 PointerProperties pointerProperties[pointerCount];
1460 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001461
chaviwd1c23182019-12-20 18:44:56 -08001462 for (size_t i = 0; i < pointerCount; i++) {
1463 pointerProperties[i].clear();
1464 pointerProperties[i].id = i;
1465 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001466
chaviwd1c23182019-12-20 18:44:56 -08001467 pointerCoords[i].clear();
1468 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1469 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1470 }
Jackal Guof9696682018-10-05 12:23:23 +08001471
1472 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1473 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001474 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001475 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1476 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001477 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1478 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001479 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1480 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001481
1482 return args;
1483}
1484
chaviwd1c23182019-12-20 18:44:56 -08001485static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1486 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1487}
1488
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001489static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1490 const PointerCaptureRequest& request) {
1491 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001492}
1493
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001494/**
1495 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1496 * broken channel.
1497 */
1498TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1499 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1500 sp<FakeWindowHandle> window =
1501 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1502 ADISPLAY_ID_DEFAULT);
1503
1504 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1505
1506 // Window closes its channel, but the window remains.
1507 window->destroyReceiver();
1508 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1509}
1510
Arthur Hungb92218b2018-08-14 12:00:21 +08001511TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001512 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001513 sp<FakeWindowHandle> window =
1514 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001515
Arthur Hung72d8dc32020-03-28 00:48:39 +00001516 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001517 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1518 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1519 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001520
1521 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001522 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001523}
1524
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001525TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1526 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1527 sp<FakeWindowHandle> window =
1528 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1529
1530 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1531 // Inject a MotionEvent to an unknown display.
1532 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1533 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1534 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1535
1536 // Window should receive motion event.
1537 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1538}
1539
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001540/**
1541 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1542 * To ensure that window receives only events that were directly inside of it, add
1543 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1544 * when finding touched windows.
1545 * This test serves as a sanity check for the next test, where setInputWindows is
1546 * called twice.
1547 */
1548TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001549 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001550 sp<FakeWindowHandle> window =
1551 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1552 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001553 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001554
1555 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001556 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001557 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1558 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001559 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001560
1561 // Window should receive motion event.
1562 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1563}
1564
1565/**
1566 * Calling setInputWindows twice, with the same info, should not cause any issues.
1567 * To ensure that window receives only events that were directly inside of it, add
1568 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1569 * when finding touched windows.
1570 */
1571TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001572 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001573 sp<FakeWindowHandle> window =
1574 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1575 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001576 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001577
1578 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1579 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001580 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001581 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1582 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001583 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001584
1585 // Window should receive motion event.
1586 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1587}
1588
Arthur Hungb92218b2018-08-14 12:00:21 +08001589// The foreground window should receive the first touch down event.
1590TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001591 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001592 sp<FakeWindowHandle> windowTop =
1593 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1594 sp<FakeWindowHandle> windowSecond =
1595 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001596
Arthur Hung72d8dc32020-03-28 00:48:39 +00001597 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001598 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1599 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1600 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001601
1602 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001603 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001604 windowSecond->assertNoEvents();
1605}
1606
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001607/**
1608 * Two windows: A top window, and a wallpaper behind the window.
1609 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1610 * gets ACTION_CANCEL.
1611 * 1. foregroundWindow <-- has wallpaper (hasWallpaper=true)
1612 * 2. wallpaperWindow <-- is wallpaper (type=InputWindowInfo::Type::WALLPAPER)
1613 */
1614TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1615 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1616 sp<FakeWindowHandle> foregroundWindow =
1617 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1618 foregroundWindow->setHasWallpaper(true);
1619 sp<FakeWindowHandle> wallpaperWindow =
1620 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1621 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1622 constexpr int expectedWallpaperFlags =
1623 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1624
1625 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1626 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1627 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1628 {100, 200}))
1629 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1630
1631 // Both foreground window and its wallpaper should receive the touch down
1632 foregroundWindow->consumeMotionDown();
1633 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1634
1635 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1636 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1637 ADISPLAY_ID_DEFAULT, {110, 200}))
1638 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1639
1640 foregroundWindow->consumeMotionMove();
1641 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1642
1643 // Now the foreground window goes away, but the wallpaper stays
1644 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1645 foregroundWindow->consumeMotionCancel();
1646 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1647 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1648}
1649
1650/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001651 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1652 * with the following differences:
1653 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1654 * clean up the connection.
1655 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1656 * Ensure that there's no crash in the dispatcher.
1657 */
1658TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1659 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1660 sp<FakeWindowHandle> foregroundWindow =
1661 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1662 foregroundWindow->setHasWallpaper(true);
1663 sp<FakeWindowHandle> wallpaperWindow =
1664 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1665 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1666 constexpr int expectedWallpaperFlags =
1667 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1668
1669 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1670 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1671 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1672 {100, 200}))
1673 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1674
1675 // Both foreground window and its wallpaper should receive the touch down
1676 foregroundWindow->consumeMotionDown();
1677 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1678
1679 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1680 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1681 ADISPLAY_ID_DEFAULT, {110, 200}))
1682 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1683
1684 foregroundWindow->consumeMotionMove();
1685 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1686
1687 // Wallpaper closes its channel, but the window remains.
1688 wallpaperWindow->destroyReceiver();
1689 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1690
1691 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1692 // is no longer valid.
1693 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1694 foregroundWindow->consumeMotionCancel();
1695}
1696
1697/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001698 * A single window that receives touch (on top), and a wallpaper window underneath it.
1699 * The top window gets a multitouch gesture.
1700 * Ensure that wallpaper gets the same gesture.
1701 */
1702TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1703 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1704 sp<FakeWindowHandle> window =
1705 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1706 window->setHasWallpaper(true);
1707
1708 sp<FakeWindowHandle> wallpaperWindow =
1709 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1710 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1711 constexpr int expectedWallpaperFlags =
1712 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1713
1714 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1715
1716 // Touch down on top window
1717 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1718 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1719 {100, 100}))
1720 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1721
1722 // Both top window and its wallpaper should receive the touch down
1723 window->consumeMotionDown();
1724 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1725
1726 // Second finger down on the top window
1727 const MotionEvent secondFingerDownEvent =
1728 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1729 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1730 AINPUT_SOURCE_TOUCHSCREEN)
1731 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1732 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1733 .x(100)
1734 .y(100))
1735 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1736 .x(150)
1737 .y(150))
1738 .build();
1739 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1740 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1741 InputEventInjectionSync::WAIT_FOR_RESULT))
1742 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1743
1744 window->consumeMotionPointerDown(1 /* pointerIndex */);
1745 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1746 expectedWallpaperFlags);
1747 window->assertNoEvents();
1748 wallpaperWindow->assertNoEvents();
1749}
1750
1751/**
1752 * Two windows: a window on the left and window on the right.
1753 * A third window, wallpaper, is behind both windows, and spans both top windows.
1754 * The first touch down goes to the left window. A second pointer touches down on the right window.
1755 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1756 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1757 * ACTION_POINTER_DOWN(1).
1758 */
1759TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1760 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1761 sp<FakeWindowHandle> leftWindow =
1762 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1763 leftWindow->setFrame(Rect(0, 0, 200, 200));
1764 leftWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1765 leftWindow->setHasWallpaper(true);
1766
1767 sp<FakeWindowHandle> rightWindow =
1768 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1769 rightWindow->setFrame(Rect(200, 0, 400, 200));
1770 rightWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1771 rightWindow->setHasWallpaper(true);
1772
1773 sp<FakeWindowHandle> wallpaperWindow =
1774 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1775 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
1776 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1777 constexpr int expectedWallpaperFlags =
1778 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1779
1780 mDispatcher->setInputWindows(
1781 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1782
1783 // Touch down on left window
1784 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1785 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1786 {100, 100}))
1787 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1788
1789 // Both foreground window and its wallpaper should receive the touch down
1790 leftWindow->consumeMotionDown();
1791 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1792
1793 // Second finger down on the right window
1794 const MotionEvent secondFingerDownEvent =
1795 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1796 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1797 AINPUT_SOURCE_TOUCHSCREEN)
1798 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1799 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1800 .x(100)
1801 .y(100))
1802 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1803 .x(300)
1804 .y(100))
1805 .build();
1806 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1807 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1808 InputEventInjectionSync::WAIT_FOR_RESULT))
1809 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1810
1811 leftWindow->consumeMotionMove();
1812 // Since the touch is split, right window gets ACTION_DOWN
1813 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1814 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1815 expectedWallpaperFlags);
1816
1817 // Now, leftWindow, which received the first finger, disappears.
1818 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1819 leftWindow->consumeMotionCancel();
1820 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1821 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1822
1823 // The pointer that's still down on the right window moves, and goes to the right window only.
1824 // As far as the dispatcher's concerned though, both pointers are still present.
1825 const MotionEvent secondFingerMoveEvent =
1826 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1827 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1828 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1829 .x(100)
1830 .y(100))
1831 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1832 .x(310)
1833 .y(110))
1834 .build();
1835 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1836 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1837 InputEventInjectionSync::WAIT_FOR_RESULT));
1838 rightWindow->consumeMotionMove();
1839
1840 leftWindow->assertNoEvents();
1841 rightWindow->assertNoEvents();
1842 wallpaperWindow->assertNoEvents();
1843}
1844
Garfield Tandf26e862020-07-01 20:18:19 -07001845TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001846 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001847 sp<FakeWindowHandle> windowLeft =
1848 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1849 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001850 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001851 sp<FakeWindowHandle> windowRight =
1852 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1853 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001854 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001855
1856 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1857
1858 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1859
1860 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001861 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001862 injectMotionEvent(mDispatcher,
1863 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1864 AINPUT_SOURCE_MOUSE)
1865 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1866 .x(900)
1867 .y(400))
1868 .build()));
1869 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1870 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1871 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1872 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1873
1874 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001875 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001876 injectMotionEvent(mDispatcher,
1877 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1878 AINPUT_SOURCE_MOUSE)
1879 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1880 .x(300)
1881 .y(400))
1882 .build()));
1883 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1884 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1885 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1886 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1887 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1888 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1889
1890 // Inject a series of mouse events for a mouse click
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_DOWN, AINPUT_SOURCE_MOUSE)
1894 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1895 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1896 .x(300)
1897 .y(400))
1898 .build()));
1899 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1900
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001901 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001902 injectMotionEvent(mDispatcher,
1903 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1904 AINPUT_SOURCE_MOUSE)
1905 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1906 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1907 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1908 .x(300)
1909 .y(400))
1910 .build()));
1911 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1912 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1913
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001914 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001915 injectMotionEvent(mDispatcher,
1916 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1917 AINPUT_SOURCE_MOUSE)
1918 .buttonState(0)
1919 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1920 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1921 .x(300)
1922 .y(400))
1923 .build()));
1924 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1925 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1926
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001927 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001928 injectMotionEvent(mDispatcher,
1929 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1930 .buttonState(0)
1931 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1932 .x(300)
1933 .y(400))
1934 .build()));
1935 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1936
1937 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001938 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001939 injectMotionEvent(mDispatcher,
1940 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1941 AINPUT_SOURCE_MOUSE)
1942 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1943 .x(900)
1944 .y(400))
1945 .build()));
1946 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1947 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1948 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1949 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1950 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1951 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1952}
1953
1954// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1955// directly in this test.
1956TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001957 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001958 sp<FakeWindowHandle> window =
1959 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1960 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001961 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001962
1963 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1964
1965 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1966
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001967 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001968 injectMotionEvent(mDispatcher,
1969 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1970 AINPUT_SOURCE_MOUSE)
1971 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1972 .x(300)
1973 .y(400))
1974 .build()));
1975 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1976 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1977
1978 // Inject a series of mouse events for a mouse click
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_DOWN, AINPUT_SOURCE_MOUSE)
1982 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1983 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1984 .x(300)
1985 .y(400))
1986 .build()));
1987 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1988
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001989 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001990 injectMotionEvent(mDispatcher,
1991 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1992 AINPUT_SOURCE_MOUSE)
1993 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1994 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1995 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1996 .x(300)
1997 .y(400))
1998 .build()));
1999 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2000 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2001
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002002 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002003 injectMotionEvent(mDispatcher,
2004 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2005 AINPUT_SOURCE_MOUSE)
2006 .buttonState(0)
2007 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2008 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2009 .x(300)
2010 .y(400))
2011 .build()));
2012 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2013 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
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_UP, AINPUT_SOURCE_MOUSE)
2018 .buttonState(0)
2019 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2020 .x(300)
2021 .y(400))
2022 .build()));
2023 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2024
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002025 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002026 injectMotionEvent(mDispatcher,
2027 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2028 AINPUT_SOURCE_MOUSE)
2029 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2030 .x(300)
2031 .y(400))
2032 .build()));
2033 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2034 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2035}
2036
Garfield Tan00f511d2019-06-12 16:55:40 -07002037TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002038 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002039
2040 sp<FakeWindowHandle> windowLeft =
2041 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2042 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002043 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002044 sp<FakeWindowHandle> windowRight =
2045 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2046 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05002047 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002048
2049 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2050
Arthur Hung72d8dc32020-03-28 00:48:39 +00002051 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002052
2053 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2054 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002055 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002056 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002057 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002058 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002059 windowRight->assertNoEvents();
2060}
2061
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002062TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002063 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002064 sp<FakeWindowHandle> window =
2065 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002066 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002067
Arthur Hung72d8dc32020-03-28 00:48:39 +00002068 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002069 setFocusedWindow(window);
2070
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002071 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002072
2073 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2074 mDispatcher->notifyKey(&keyArgs);
2075
2076 // Window should receive key down event.
2077 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2078
2079 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2080 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002081 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002082 mDispatcher->notifyDeviceReset(&args);
2083 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2084 AKEY_EVENT_FLAG_CANCELED);
2085}
2086
2087TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002088 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002089 sp<FakeWindowHandle> window =
2090 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2091
Arthur Hung72d8dc32020-03-28 00:48:39 +00002092 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002093
2094 NotifyMotionArgs motionArgs =
2095 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2096 ADISPLAY_ID_DEFAULT);
2097 mDispatcher->notifyMotion(&motionArgs);
2098
2099 // Window should receive motion down event.
2100 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2101
2102 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2103 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002104 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002105 mDispatcher->notifyDeviceReset(&args);
2106 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2107 0 /*expectedFlags*/);
2108}
2109
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002110/**
2111 * Ensure the correct coordinate spaces are used by InputDispatcher.
2112 *
2113 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2114 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2115 * space.
2116 */
2117class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2118public:
2119 void SetUp() override {
2120 InputDispatcherTest::SetUp();
2121 mDisplayInfos.clear();
2122 mWindowInfos.clear();
2123 }
2124
2125 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2126 gui::DisplayInfo info;
2127 info.displayId = displayId;
2128 info.transform = transform;
2129 mDisplayInfos.push_back(std::move(info));
2130 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2131 }
2132
2133 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2134 mWindowInfos.push_back(*windowHandle->getInfo());
2135 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2136 }
2137
2138 // Set up a test scenario where the display has a scaled projection and there are two windows
2139 // on the display.
2140 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2141 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2142 // respectively.
2143 ui::Transform displayTransform;
2144 displayTransform.set(2, 0, 0, 4);
2145 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2146
2147 std::shared_ptr<FakeApplicationHandle> application =
2148 std::make_shared<FakeApplicationHandle>();
2149
2150 // Add two windows to the display. Their frames are represented in the display space.
2151 sp<FakeWindowHandle> firstWindow =
2152 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2153 firstWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2154 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2155 addWindow(firstWindow);
2156
2157 sp<FakeWindowHandle> secondWindow =
2158 new FakeWindowHandle(application, mDispatcher, "Second Window",
2159 ADISPLAY_ID_DEFAULT);
2160 secondWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2161 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2162 addWindow(secondWindow);
2163 return {std::move(firstWindow), std::move(secondWindow)};
2164 }
2165
2166private:
2167 std::vector<gui::DisplayInfo> mDisplayInfos;
2168 std::vector<gui::WindowInfo> mWindowInfos;
2169};
2170
2171TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2172 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2173 // Send down to the first window. The point is represented in the display space. The point is
2174 // selected so that if the hit test was done with the transform applied to it, then it would
2175 // end up in the incorrect window.
2176 NotifyMotionArgs downMotionArgs =
2177 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2178 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2179 mDispatcher->notifyMotion(&downMotionArgs);
2180
2181 firstWindow->consumeMotionDown();
2182 secondWindow->assertNoEvents();
2183}
2184
2185// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2186// the event should be treated as being in the logical display space.
2187TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2188 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2189 // Send down to the first window. The point is represented in the logical display space. The
2190 // point is selected so that if the hit test was done in logical display space, then it would
2191 // end up in the incorrect window.
2192 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2193 PointF{75 * 2, 55 * 4});
2194
2195 firstWindow->consumeMotionDown();
2196 secondWindow->assertNoEvents();
2197}
2198
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002199// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2200// event should be treated as being in the logical display space.
2201TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2202 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2203
2204 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2205 ui::Transform injectedEventTransform;
2206 injectedEventTransform.set(matrix);
2207 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2208 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2209
2210 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2211 .displayId(ADISPLAY_ID_DEFAULT)
2212 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2213 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2214 .x(untransformedPoint.x)
2215 .y(untransformedPoint.y))
2216 .build();
2217 event.transform(matrix);
2218
2219 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2220 InputEventInjectionSync::WAIT_FOR_RESULT);
2221
2222 firstWindow->consumeMotionDown();
2223 secondWindow->assertNoEvents();
2224}
2225
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002226TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2227 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2228
2229 // Send down to the second window.
2230 NotifyMotionArgs downMotionArgs =
2231 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2232 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2233 mDispatcher->notifyMotion(&downMotionArgs);
2234
2235 firstWindow->assertNoEvents();
2236 const MotionEvent* event = secondWindow->consumeMotion();
2237 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2238
2239 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2240 EXPECT_EQ(300, event->getRawX(0));
2241 EXPECT_EQ(880, event->getRawY(0));
2242
2243 // Ensure that the x and y values are in the window's coordinate space.
2244 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2245 // the logical display space. This will be the origin of the window space.
2246 EXPECT_EQ(100, event->getX(0));
2247 EXPECT_EQ(80, event->getY(0));
2248}
2249
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002250using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2251 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002252
2253class TransferTouchFixture : public InputDispatcherTest,
2254 public ::testing::WithParamInterface<TransferFunction> {};
2255
2256TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002257 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002258
2259 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002260 sp<FakeWindowHandle> firstWindow =
2261 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2262 sp<FakeWindowHandle> secondWindow =
2263 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002264
2265 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002266 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002267
2268 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002269 NotifyMotionArgs downMotionArgs =
2270 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2271 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002272 mDispatcher->notifyMotion(&downMotionArgs);
2273 // Only the first window should get the down event
2274 firstWindow->consumeMotionDown();
2275 secondWindow->assertNoEvents();
2276
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002277 // Transfer touch to the second window
2278 TransferFunction f = GetParam();
2279 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2280 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002281 // The first window gets cancel and the second gets down
2282 firstWindow->consumeMotionCancel();
2283 secondWindow->consumeMotionDown();
2284
2285 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002286 NotifyMotionArgs upMotionArgs =
2287 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2288 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002289 mDispatcher->notifyMotion(&upMotionArgs);
2290 // The first window gets no events and the second gets up
2291 firstWindow->assertNoEvents();
2292 secondWindow->consumeMotionUp();
2293}
2294
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002295TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002296 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002297
2298 PointF touchPoint = {10, 10};
2299
2300 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002301 sp<FakeWindowHandle> firstWindow =
2302 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2303 sp<FakeWindowHandle> secondWindow =
2304 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002305
2306 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002307 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002308
2309 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002310 NotifyMotionArgs downMotionArgs =
2311 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2312 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002313 mDispatcher->notifyMotion(&downMotionArgs);
2314 // Only the first window should get the down event
2315 firstWindow->consumeMotionDown();
2316 secondWindow->assertNoEvents();
2317
2318 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002319 NotifyMotionArgs pointerDownMotionArgs =
2320 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2321 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2322 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2323 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002324 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2325 // Only the first window should get the pointer down event
2326 firstWindow->consumeMotionPointerDown(1);
2327 secondWindow->assertNoEvents();
2328
2329 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002330 TransferFunction f = GetParam();
2331 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2332 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002333 // The first window gets cancel and the second gets down and pointer down
2334 firstWindow->consumeMotionCancel();
2335 secondWindow->consumeMotionDown();
2336 secondWindow->consumeMotionPointerDown(1);
2337
2338 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002339 NotifyMotionArgs pointerUpMotionArgs =
2340 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2341 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2342 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2343 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002344 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2345 // The first window gets nothing and the second gets pointer up
2346 firstWindow->assertNoEvents();
2347 secondWindow->consumeMotionPointerUp(1);
2348
2349 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002350 NotifyMotionArgs upMotionArgs =
2351 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2352 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002353 mDispatcher->notifyMotion(&upMotionArgs);
2354 // The first window gets nothing and the second gets up
2355 firstWindow->assertNoEvents();
2356 secondWindow->consumeMotionUp();
2357}
2358
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002359// For the cases of single pointer touch and two pointers non-split touch, the api's
2360// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2361// for the case where there are multiple pointers split across several windows.
2362INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2363 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002364 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2365 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002366 return dispatcher->transferTouch(destChannelToken);
2367 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002368 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2369 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002370 return dispatcher->transferTouchFocus(from, to,
2371 false /*isDragAndDrop*/);
2372 }));
2373
Svet Ganov5d3bc372020-01-26 23:11:07 -08002374TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002375 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002376
2377 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002378 sp<FakeWindowHandle> firstWindow =
2379 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002380 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002381 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002382
2383 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002384 sp<FakeWindowHandle> secondWindow =
2385 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002386 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002387 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002388
2389 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002390 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002391
2392 PointF pointInFirst = {300, 200};
2393 PointF pointInSecond = {300, 600};
2394
2395 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002396 NotifyMotionArgs firstDownMotionArgs =
2397 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2398 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002399 mDispatcher->notifyMotion(&firstDownMotionArgs);
2400 // Only the first window should get the down event
2401 firstWindow->consumeMotionDown();
2402 secondWindow->assertNoEvents();
2403
2404 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002405 NotifyMotionArgs secondDownMotionArgs =
2406 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2407 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2408 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2409 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002410 mDispatcher->notifyMotion(&secondDownMotionArgs);
2411 // The first window gets a move and the second a down
2412 firstWindow->consumeMotionMove();
2413 secondWindow->consumeMotionDown();
2414
2415 // Transfer touch focus to the second window
2416 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2417 // The first window gets cancel and the new gets pointer down (it already saw down)
2418 firstWindow->consumeMotionCancel();
2419 secondWindow->consumeMotionPointerDown(1);
2420
2421 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002422 NotifyMotionArgs pointerUpMotionArgs =
2423 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2424 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2425 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2426 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002427 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2428 // The first window gets nothing and the second gets pointer up
2429 firstWindow->assertNoEvents();
2430 secondWindow->consumeMotionPointerUp(1);
2431
2432 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002433 NotifyMotionArgs upMotionArgs =
2434 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2435 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002436 mDispatcher->notifyMotion(&upMotionArgs);
2437 // The first window gets nothing and the second gets up
2438 firstWindow->assertNoEvents();
2439 secondWindow->consumeMotionUp();
2440}
2441
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002442// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2443// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2444// touch is not supported, so the touch should continue on those windows and the transferred-to
2445// window should get nothing.
2446TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2447 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2448
2449 // Create a non touch modal window that supports split touch
2450 sp<FakeWindowHandle> firstWindow =
2451 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2452 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002453 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002454
2455 // Create a non touch modal window that supports split touch
2456 sp<FakeWindowHandle> secondWindow =
2457 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2458 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002459 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002460
2461 // Add the windows to the dispatcher
2462 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2463
2464 PointF pointInFirst = {300, 200};
2465 PointF pointInSecond = {300, 600};
2466
2467 // Send down to the first window
2468 NotifyMotionArgs firstDownMotionArgs =
2469 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2470 ADISPLAY_ID_DEFAULT, {pointInFirst});
2471 mDispatcher->notifyMotion(&firstDownMotionArgs);
2472 // Only the first window should get the down event
2473 firstWindow->consumeMotionDown();
2474 secondWindow->assertNoEvents();
2475
2476 // Send down to the second window
2477 NotifyMotionArgs secondDownMotionArgs =
2478 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2479 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2480 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2481 {pointInFirst, pointInSecond});
2482 mDispatcher->notifyMotion(&secondDownMotionArgs);
2483 // The first window gets a move and the second a down
2484 firstWindow->consumeMotionMove();
2485 secondWindow->consumeMotionDown();
2486
2487 // Transfer touch focus to the second window
2488 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2489 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2490 ASSERT_FALSE(transferred);
2491 firstWindow->assertNoEvents();
2492 secondWindow->assertNoEvents();
2493
2494 // The rest of the dispatch should proceed as normal
2495 // Send pointer up to the second window
2496 NotifyMotionArgs pointerUpMotionArgs =
2497 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2498 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2499 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2500 {pointInFirst, pointInSecond});
2501 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2502 // The first window gets MOVE and the second gets pointer up
2503 firstWindow->consumeMotionMove();
2504 secondWindow->consumeMotionUp();
2505
2506 // Send up event to the first window
2507 NotifyMotionArgs upMotionArgs =
2508 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2509 ADISPLAY_ID_DEFAULT);
2510 mDispatcher->notifyMotion(&upMotionArgs);
2511 // The first window gets nothing and the second gets up
2512 firstWindow->consumeMotionUp();
2513 secondWindow->assertNoEvents();
2514}
2515
Arthur Hungabbb9d82021-09-01 14:52:30 +00002516// This case will create two windows and one mirrored window on the default display and mirror
2517// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2518// the windows info of second display before default display.
2519TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2520 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2521 sp<FakeWindowHandle> firstWindowInPrimary =
2522 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2523 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2524 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2525 sp<FakeWindowHandle> secondWindowInPrimary =
2526 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2527 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2528 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2529
2530 sp<FakeWindowHandle> mirrorWindowInPrimary =
2531 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2532 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2533 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2534
2535 sp<FakeWindowHandle> firstWindowInSecondary =
2536 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2537 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2538 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2539
2540 sp<FakeWindowHandle> secondWindowInSecondary =
2541 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2542 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2543 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2544
2545 // Update window info, let it find window handle of second display first.
2546 mDispatcher->setInputWindows(
2547 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2548 {ADISPLAY_ID_DEFAULT,
2549 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2550
2551 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2552 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2553 {50, 50}))
2554 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2555
2556 // Window should receive motion event.
2557 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2558
2559 // Transfer touch focus
2560 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2561 secondWindowInPrimary->getToken()));
2562 // The first window gets cancel.
2563 firstWindowInPrimary->consumeMotionCancel();
2564 secondWindowInPrimary->consumeMotionDown();
2565
2566 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2567 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2568 ADISPLAY_ID_DEFAULT, {150, 50}))
2569 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2570 firstWindowInPrimary->assertNoEvents();
2571 secondWindowInPrimary->consumeMotionMove();
2572
2573 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2574 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2575 {150, 50}))
2576 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2577 firstWindowInPrimary->assertNoEvents();
2578 secondWindowInPrimary->consumeMotionUp();
2579}
2580
2581// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2582// 'transferTouch' api.
2583TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2584 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2585 sp<FakeWindowHandle> firstWindowInPrimary =
2586 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2587 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2588 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2589 sp<FakeWindowHandle> secondWindowInPrimary =
2590 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2591 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2592 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2593
2594 sp<FakeWindowHandle> mirrorWindowInPrimary =
2595 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2596 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2597 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2598
2599 sp<FakeWindowHandle> firstWindowInSecondary =
2600 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2601 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2602 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2603
2604 sp<FakeWindowHandle> secondWindowInSecondary =
2605 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2606 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2607 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2608
2609 // Update window info, let it find window handle of second display first.
2610 mDispatcher->setInputWindows(
2611 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2612 {ADISPLAY_ID_DEFAULT,
2613 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2614
2615 // Touch on second display.
2616 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2617 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2618 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2619
2620 // Window should receive motion event.
2621 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2622
2623 // Transfer touch focus
2624 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2625
2626 // The first window gets cancel.
2627 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2628 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2629
2630 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2631 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2632 SECOND_DISPLAY_ID, {150, 50}))
2633 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2634 firstWindowInPrimary->assertNoEvents();
2635 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2636
2637 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2638 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2639 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2640 firstWindowInPrimary->assertNoEvents();
2641 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2642}
2643
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002644TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002645 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002646 sp<FakeWindowHandle> window =
2647 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2648
Vishnu Nair47074b82020-08-14 11:54:47 -07002649 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002651 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002652
2653 window->consumeFocusEvent(true);
2654
2655 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2656 mDispatcher->notifyKey(&keyArgs);
2657
2658 // Window should receive key down event.
2659 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2660}
2661
2662TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002663 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002664 sp<FakeWindowHandle> window =
2665 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2666
Arthur Hung72d8dc32020-03-28 00:48:39 +00002667 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002668
2669 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2670 mDispatcher->notifyKey(&keyArgs);
2671 mDispatcher->waitForIdle();
2672
2673 window->assertNoEvents();
2674}
2675
2676// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2677TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002678 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002679 sp<FakeWindowHandle> window =
2680 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2681
Arthur Hung72d8dc32020-03-28 00:48:39 +00002682 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002683
2684 // Send key
2685 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2686 mDispatcher->notifyKey(&keyArgs);
2687 // Send motion
2688 NotifyMotionArgs motionArgs =
2689 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2690 ADISPLAY_ID_DEFAULT);
2691 mDispatcher->notifyMotion(&motionArgs);
2692
2693 // Window should receive only the motion event
2694 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2695 window->assertNoEvents(); // Key event or focus event will not be received
2696}
2697
arthurhungea3f4fc2020-12-21 23:18:53 +08002698TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2699 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2700
2701 // Create first non touch modal window that supports split touch
2702 sp<FakeWindowHandle> firstWindow =
2703 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2704 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002705 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002706
2707 // Create second non touch modal window that supports split touch
2708 sp<FakeWindowHandle> secondWindow =
2709 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2710 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002711 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002712
2713 // Add the windows to the dispatcher
2714 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2715
2716 PointF pointInFirst = {300, 200};
2717 PointF pointInSecond = {300, 600};
2718
2719 // Send down to the first window
2720 NotifyMotionArgs firstDownMotionArgs =
2721 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2722 ADISPLAY_ID_DEFAULT, {pointInFirst});
2723 mDispatcher->notifyMotion(&firstDownMotionArgs);
2724 // Only the first window should get the down event
2725 firstWindow->consumeMotionDown();
2726 secondWindow->assertNoEvents();
2727
2728 // Send down to the second window
2729 NotifyMotionArgs secondDownMotionArgs =
2730 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2731 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2732 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2733 {pointInFirst, pointInSecond});
2734 mDispatcher->notifyMotion(&secondDownMotionArgs);
2735 // The first window gets a move and the second a down
2736 firstWindow->consumeMotionMove();
2737 secondWindow->consumeMotionDown();
2738
2739 // Send pointer cancel to the second window
2740 NotifyMotionArgs pointerUpMotionArgs =
2741 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2742 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2743 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2744 {pointInFirst, pointInSecond});
2745 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2746 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2747 // The first window gets move and the second gets cancel.
2748 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2749 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2750
2751 // Send up event.
2752 NotifyMotionArgs upMotionArgs =
2753 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2754 ADISPLAY_ID_DEFAULT);
2755 mDispatcher->notifyMotion(&upMotionArgs);
2756 // The first window gets up and the second gets nothing.
2757 firstWindow->consumeMotionUp();
2758 secondWindow->assertNoEvents();
2759}
2760
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002761TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2762 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2763
2764 sp<FakeWindowHandle> window =
2765 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2766 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2767 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2768 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2769 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2770
2771 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2772 window->assertNoEvents();
2773 mDispatcher->waitForIdle();
2774}
2775
chaviwd1c23182019-12-20 18:44:56 -08002776class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002777public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002778 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002779 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07002780 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002781 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002782 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002783 }
2784
chaviwd1c23182019-12-20 18:44:56 -08002785 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2786
2787 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2788 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2789 expectedDisplayId, expectedFlags);
2790 }
2791
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002792 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2793
2794 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2795
chaviwd1c23182019-12-20 18:44:56 -08002796 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2797 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2798 expectedDisplayId, expectedFlags);
2799 }
2800
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002801 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2802 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2803 expectedDisplayId, expectedFlags);
2804 }
2805
chaviwd1c23182019-12-20 18:44:56 -08002806 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2807 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2808 expectedDisplayId, expectedFlags);
2809 }
2810
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002811 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2812 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2813 expectedDisplayId, expectedFlags);
2814 }
2815
Arthur Hungfbfa5722021-11-16 02:45:54 +00002816 void consumeMotionPointerDown(int32_t pointerIdx) {
2817 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2818 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2819 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2820 0 /*expectedFlags*/);
2821 }
2822
Evan Rosky84f07f02021-04-16 10:42:42 -07002823 MotionEvent* consumeMotion() {
2824 InputEvent* event = mInputReceiver->consume();
2825 if (!event) {
2826 ADD_FAILURE() << "No event was produced";
2827 return nullptr;
2828 }
2829 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2830 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2831 return nullptr;
2832 }
2833 return static_cast<MotionEvent*>(event);
2834 }
2835
chaviwd1c23182019-12-20 18:44:56 -08002836 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2837
2838private:
2839 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002840};
2841
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002842using InputDispatcherMonitorTest = InputDispatcherTest;
2843
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002844/**
2845 * Two entities that receive touch: A window, and a global monitor.
2846 * The touch goes to the window, and then the window disappears.
2847 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2848 * for the monitor, as well.
2849 * 1. foregroundWindow
2850 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2851 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002852TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002853 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2854 sp<FakeWindowHandle> window =
2855 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2856
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002857 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002858
2859 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2860 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2861 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2862 {100, 200}))
2863 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2864
2865 // Both the foreground window and the global monitor should receive the touch down
2866 window->consumeMotionDown();
2867 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2868
2869 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2870 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2871 ADISPLAY_ID_DEFAULT, {110, 200}))
2872 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2873
2874 window->consumeMotionMove();
2875 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2876
2877 // Now the foreground window goes away
2878 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2879 window->consumeMotionCancel();
2880 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2881
2882 // If more events come in, there will be no more foreground window to send them to. This will
2883 // cause a cancel for the monitor, as well.
2884 ASSERT_EQ(InputEventInjectionResult::FAILED,
2885 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2886 ADISPLAY_ID_DEFAULT, {120, 200}))
2887 << "Injection should fail because the window was removed";
2888 window->assertNoEvents();
2889 // Global monitor now gets the cancel
2890 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2891}
2892
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002893TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002894 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002895 sp<FakeWindowHandle> window =
2896 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002897 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002898
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002899 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002900
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002901 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002902 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002903 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002904 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002905 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002906}
2907
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002908TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
2909 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002910
Chris Yea209fde2020-07-22 13:54:51 -07002911 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002912 sp<FakeWindowHandle> window =
2913 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002914 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002915
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002916 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002917 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002918 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002919 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002920 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002921
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002922 // Pilfer pointers from the monitor.
2923 // This should not do anything and the window should continue to receive events.
2924 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00002925
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002926 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002927 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2928 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002929 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002930
2931 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2932 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002933}
2934
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002935TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07002936 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2937 sp<FakeWindowHandle> window =
2938 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2939 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2940 window->setWindowOffset(20, 40);
2941 window->setWindowTransform(0, 1, -1, 0);
2942
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002943 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07002944
2945 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2946 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2947 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2948 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2949 MotionEvent* event = monitor.consumeMotion();
2950 // Even though window has transform, gesture monitor must not.
2951 ASSERT_EQ(ui::Transform(), event->getTransform());
2952}
2953
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002954TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002955 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002956 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00002957
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002958 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00002959 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002960 << "Injection should fail if there is a monitor, but no touchable window";
2961 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00002962}
2963
chaviw81e2bb92019-12-18 15:03:51 -08002964TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002965 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002966 sp<FakeWindowHandle> window =
2967 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2968
Arthur Hung72d8dc32020-03-28 00:48:39 +00002969 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002970
2971 NotifyMotionArgs motionArgs =
2972 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2973 ADISPLAY_ID_DEFAULT);
2974
2975 mDispatcher->notifyMotion(&motionArgs);
2976 // Window should receive motion down event.
2977 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2978
2979 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002980 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002981 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2982 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2983 motionArgs.pointerCoords[0].getX() - 10);
2984
2985 mDispatcher->notifyMotion(&motionArgs);
2986 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2987 0 /*expectedFlags*/);
2988}
2989
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002990/**
2991 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2992 * the device default right away. In the test scenario, we check both the default value,
2993 * and the action of enabling / disabling.
2994 */
2995TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002996 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002997 sp<FakeWindowHandle> window =
2998 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
2999
3000 // Set focused application.
3001 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003002 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003003
3004 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003005 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003006 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003007 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3008
3009 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003010 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003011 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003012 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3013
3014 SCOPED_TRACE("Disable touch mode");
3015 mDispatcher->setInTouchMode(false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003016 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003017 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003018 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003019 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003020 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3021
3022 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003023 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003024 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003025 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3026
3027 SCOPED_TRACE("Enable touch mode again");
3028 mDispatcher->setInTouchMode(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003029 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003030 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003031 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003032 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003033 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3034
3035 window->assertNoEvents();
3036}
3037
Gang Wange9087892020-01-07 12:17:14 -05003038TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003039 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003040 sp<FakeWindowHandle> window =
3041 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3042
3043 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003044 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003045
Arthur Hung72d8dc32020-03-28 00:48:39 +00003046 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003047 setFocusedWindow(window);
3048
Gang Wange9087892020-01-07 12:17:14 -05003049 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3050
3051 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3052 mDispatcher->notifyKey(&keyArgs);
3053
3054 InputEvent* event = window->consume();
3055 ASSERT_NE(event, nullptr);
3056
3057 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3058 ASSERT_NE(verified, nullptr);
3059 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3060
3061 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3062 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3063 ASSERT_EQ(keyArgs.source, verified->source);
3064 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3065
3066 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3067
3068 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003069 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003070 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003071 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3072 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3073 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3074 ASSERT_EQ(0, verifiedKey.repeatCount);
3075}
3076
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003077TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003078 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003079 sp<FakeWindowHandle> window =
3080 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3081
3082 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3083
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003084 ui::Transform transform;
3085 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3086
3087 gui::DisplayInfo displayInfo;
3088 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3089 displayInfo.transform = transform;
3090
3091 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003092
3093 NotifyMotionArgs motionArgs =
3094 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3095 ADISPLAY_ID_DEFAULT);
3096 mDispatcher->notifyMotion(&motionArgs);
3097
3098 InputEvent* event = window->consume();
3099 ASSERT_NE(event, nullptr);
3100
3101 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3102 ASSERT_NE(verified, nullptr);
3103 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3104
3105 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3106 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3107 EXPECT_EQ(motionArgs.source, verified->source);
3108 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3109
3110 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3111
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003112 const vec2 rawXY =
3113 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3114 motionArgs.pointerCoords[0].getXYValue());
3115 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3116 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003117 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003118 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003119 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003120 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3121 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3122}
3123
chaviw09c8d2d2020-08-24 15:48:26 -07003124/**
3125 * Ensure that separate calls to sign the same data are generating the same key.
3126 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3127 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3128 * tests.
3129 */
3130TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3131 KeyEvent event = getTestKeyEvent();
3132 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3133
3134 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3135 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3136 ASSERT_EQ(hmac1, hmac2);
3137}
3138
3139/**
3140 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3141 */
3142TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3143 KeyEvent event = getTestKeyEvent();
3144 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3145 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3146
3147 verifiedEvent.deviceId += 1;
3148 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3149
3150 verifiedEvent.source += 1;
3151 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3152
3153 verifiedEvent.eventTimeNanos += 1;
3154 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3155
3156 verifiedEvent.displayId += 1;
3157 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3158
3159 verifiedEvent.action += 1;
3160 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3161
3162 verifiedEvent.downTimeNanos += 1;
3163 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3164
3165 verifiedEvent.flags += 1;
3166 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3167
3168 verifiedEvent.keyCode += 1;
3169 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3170
3171 verifiedEvent.scanCode += 1;
3172 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3173
3174 verifiedEvent.metaState += 1;
3175 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3176
3177 verifiedEvent.repeatCount += 1;
3178 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3179}
3180
Vishnu Nair958da932020-08-21 17:12:37 -07003181TEST_F(InputDispatcherTest, SetFocusedWindow) {
3182 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3183 sp<FakeWindowHandle> windowTop =
3184 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3185 sp<FakeWindowHandle> windowSecond =
3186 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3187 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3188
3189 // Top window is also focusable but is not granted focus.
3190 windowTop->setFocusable(true);
3191 windowSecond->setFocusable(true);
3192 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3193 setFocusedWindow(windowSecond);
3194
3195 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003196 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3197 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003198
3199 // Focused window should receive event.
3200 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3201 windowTop->assertNoEvents();
3202}
3203
3204TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3205 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3206 sp<FakeWindowHandle> window =
3207 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3208 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3209
3210 window->setFocusable(true);
3211 // Release channel for window is no longer valid.
3212 window->releaseChannel();
3213 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3214 setFocusedWindow(window);
3215
3216 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003217 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3218 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003219
3220 // window channel is invalid, so it should not receive any input event.
3221 window->assertNoEvents();
3222}
3223
3224TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3225 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3226 sp<FakeWindowHandle> window =
3227 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3228 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3229
3230 // Window is not focusable.
3231 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3232 setFocusedWindow(window);
3233
3234 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003235 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3236 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003237
3238 // window is invalid, so it should not receive any input event.
3239 window->assertNoEvents();
3240}
3241
3242TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3243 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3244 sp<FakeWindowHandle> windowTop =
3245 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3246 sp<FakeWindowHandle> windowSecond =
3247 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3248 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3249
3250 windowTop->setFocusable(true);
3251 windowSecond->setFocusable(true);
3252 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3253 setFocusedWindow(windowTop);
3254 windowTop->consumeFocusEvent(true);
3255
3256 setFocusedWindow(windowSecond, windowTop);
3257 windowSecond->consumeFocusEvent(true);
3258 windowTop->consumeFocusEvent(false);
3259
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003260 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3261 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003262
3263 // Focused window should receive event.
3264 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3265}
3266
3267TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3268 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3269 sp<FakeWindowHandle> windowTop =
3270 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3271 sp<FakeWindowHandle> windowSecond =
3272 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3273 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3274
3275 windowTop->setFocusable(true);
3276 windowSecond->setFocusable(true);
3277 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3278 setFocusedWindow(windowSecond, windowTop);
3279
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003280 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3281 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003282
3283 // Event should be dropped.
3284 windowTop->assertNoEvents();
3285 windowSecond->assertNoEvents();
3286}
3287
3288TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3289 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3290 sp<FakeWindowHandle> window =
3291 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3292 sp<FakeWindowHandle> previousFocusedWindow =
3293 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3294 ADISPLAY_ID_DEFAULT);
3295 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3296
3297 window->setFocusable(true);
3298 previousFocusedWindow->setFocusable(true);
3299 window->setVisible(false);
3300 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3301 setFocusedWindow(previousFocusedWindow);
3302 previousFocusedWindow->consumeFocusEvent(true);
3303
3304 // Requesting focus on invisible window takes focus from currently focused window.
3305 setFocusedWindow(window);
3306 previousFocusedWindow->consumeFocusEvent(false);
3307
3308 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003309 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003310 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003311 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003312
3313 // Window does not get focus event or key down.
3314 window->assertNoEvents();
3315
3316 // Window becomes visible.
3317 window->setVisible(true);
3318 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3319
3320 // Window receives focus event.
3321 window->consumeFocusEvent(true);
3322 // Focused window receives key down.
3323 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3324}
3325
Vishnu Nair599f1412021-06-21 10:39:58 -07003326TEST_F(InputDispatcherTest, DisplayRemoved) {
3327 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3328 sp<FakeWindowHandle> window =
3329 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3330 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3331
3332 // window is granted focus.
3333 window->setFocusable(true);
3334 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3335 setFocusedWindow(window);
3336 window->consumeFocusEvent(true);
3337
3338 // When a display is removed window loses focus.
3339 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3340 window->consumeFocusEvent(false);
3341}
3342
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003343/**
3344 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3345 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3346 * of the 'slipperyEnterWindow'.
3347 *
3348 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3349 * a way so that the touched location is no longer covered by the top window.
3350 *
3351 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3352 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3353 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3354 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3355 * with ACTION_DOWN).
3356 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3357 * window moved itself away from the touched location and had Flag::SLIPPERY.
3358 *
3359 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3360 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3361 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3362 *
3363 * In this test, we ensure that the event received by the bottom window has
3364 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3365 */
3366TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3367 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3368 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3369
3370 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3371 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3372
3373 sp<FakeWindowHandle> slipperyExitWindow =
3374 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003375 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003376 // Make sure this one overlaps the bottom window
3377 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3378 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3379 // one. Windows with the same owner are not considered to be occluding each other.
3380 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3381
3382 sp<FakeWindowHandle> slipperyEnterWindow =
3383 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3384 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3385
3386 mDispatcher->setInputWindows(
3387 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3388
3389 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3390 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3391 ADISPLAY_ID_DEFAULT, {{50, 50}});
3392 mDispatcher->notifyMotion(&args);
3393 slipperyExitWindow->consumeMotionDown();
3394 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3395 mDispatcher->setInputWindows(
3396 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3397
3398 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3399 ADISPLAY_ID_DEFAULT, {{51, 51}});
3400 mDispatcher->notifyMotion(&args);
3401
3402 slipperyExitWindow->consumeMotionCancel();
3403
3404 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3405 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3406}
3407
Garfield Tan1c7bc862020-01-28 13:24:04 -08003408class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3409protected:
3410 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3411 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3412
Chris Yea209fde2020-07-22 13:54:51 -07003413 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003414 sp<FakeWindowHandle> mWindow;
3415
3416 virtual void SetUp() override {
3417 mFakePolicy = new FakeInputDispatcherPolicy();
3418 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003419 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003420 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3421 ASSERT_EQ(OK, mDispatcher->start());
3422
3423 setUpWindow();
3424 }
3425
3426 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003427 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003428 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3429
Vishnu Nair47074b82020-08-14 11:54:47 -07003430 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003431 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003432 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003433 mWindow->consumeFocusEvent(true);
3434 }
3435
Chris Ye2ad95392020-09-01 13:44:44 -07003436 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003437 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003438 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003439 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3440 mDispatcher->notifyKey(&keyArgs);
3441
3442 // Window should receive key down event.
3443 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3444 }
3445
3446 void expectKeyRepeatOnce(int32_t repeatCount) {
3447 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3448 InputEvent* repeatEvent = mWindow->consume();
3449 ASSERT_NE(nullptr, repeatEvent);
3450
3451 uint32_t eventType = repeatEvent->getType();
3452 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3453
3454 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3455 uint32_t eventAction = repeatKeyEvent->getAction();
3456 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3457 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3458 }
3459
Chris Ye2ad95392020-09-01 13:44:44 -07003460 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003461 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003462 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003463 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3464 mDispatcher->notifyKey(&keyArgs);
3465
3466 // Window should receive key down event.
3467 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3468 0 /*expectedFlags*/);
3469 }
3470};
3471
3472TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003473 sendAndConsumeKeyDown(1 /* deviceId */);
3474 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3475 expectKeyRepeatOnce(repeatCount);
3476 }
3477}
3478
3479TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3480 sendAndConsumeKeyDown(1 /* deviceId */);
3481 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3482 expectKeyRepeatOnce(repeatCount);
3483 }
3484 sendAndConsumeKeyDown(2 /* deviceId */);
3485 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003486 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3487 expectKeyRepeatOnce(repeatCount);
3488 }
3489}
3490
3491TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003492 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003493 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003494 sendAndConsumeKeyUp(1 /* deviceId */);
3495 mWindow->assertNoEvents();
3496}
3497
3498TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3499 sendAndConsumeKeyDown(1 /* deviceId */);
3500 expectKeyRepeatOnce(1 /*repeatCount*/);
3501 sendAndConsumeKeyDown(2 /* deviceId */);
3502 expectKeyRepeatOnce(1 /*repeatCount*/);
3503 // Stale key up from device 1.
3504 sendAndConsumeKeyUp(1 /* deviceId */);
3505 // Device 2 is still down, keep repeating
3506 expectKeyRepeatOnce(2 /*repeatCount*/);
3507 expectKeyRepeatOnce(3 /*repeatCount*/);
3508 // Device 2 key up
3509 sendAndConsumeKeyUp(2 /* deviceId */);
3510 mWindow->assertNoEvents();
3511}
3512
3513TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3514 sendAndConsumeKeyDown(1 /* deviceId */);
3515 expectKeyRepeatOnce(1 /*repeatCount*/);
3516 sendAndConsumeKeyDown(2 /* deviceId */);
3517 expectKeyRepeatOnce(1 /*repeatCount*/);
3518 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3519 sendAndConsumeKeyUp(2 /* deviceId */);
3520 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003521 mWindow->assertNoEvents();
3522}
3523
liushenxiang42232912021-05-21 20:24:09 +08003524TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3525 sendAndConsumeKeyDown(DEVICE_ID);
3526 expectKeyRepeatOnce(1 /*repeatCount*/);
3527 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3528 mDispatcher->notifyDeviceReset(&args);
3529 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3530 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3531 mWindow->assertNoEvents();
3532}
3533
Garfield Tan1c7bc862020-01-28 13:24:04 -08003534TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003535 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003536 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3537 InputEvent* repeatEvent = mWindow->consume();
3538 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3539 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3540 IdGenerator::getSource(repeatEvent->getId()));
3541 }
3542}
3543
3544TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003545 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003546
3547 std::unordered_set<int32_t> idSet;
3548 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3549 InputEvent* repeatEvent = mWindow->consume();
3550 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3551 int32_t id = repeatEvent->getId();
3552 EXPECT_EQ(idSet.end(), idSet.find(id));
3553 idSet.insert(id);
3554 }
3555}
3556
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003557/* Test InputDispatcher for MultiDisplay */
3558class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3559public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003560 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003561 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003562
Chris Yea209fde2020-07-22 13:54:51 -07003563 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003564 windowInPrimary =
3565 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003566
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003567 // Set focus window for primary display, but focused display would be second one.
3568 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003569 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003570 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003571 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003572 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003573
Chris Yea209fde2020-07-22 13:54:51 -07003574 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003575 windowInSecondary =
3576 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003577 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003578 // Set focus display to second one.
3579 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3580 // Set focus window for second display.
3581 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003582 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003583 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003584 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003585 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003586 }
3587
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003588 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003589 InputDispatcherTest::TearDown();
3590
Chris Yea209fde2020-07-22 13:54:51 -07003591 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003592 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003593 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003594 windowInSecondary.clear();
3595 }
3596
3597protected:
Chris Yea209fde2020-07-22 13:54:51 -07003598 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003599 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003600 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003601 sp<FakeWindowHandle> windowInSecondary;
3602};
3603
3604TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3605 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003606 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3607 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3608 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003609 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003610 windowInSecondary->assertNoEvents();
3611
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003612 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003613 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3614 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3615 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003616 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003617 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003618}
3619
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003620TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003621 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003622 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3623 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003624 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003625 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003626 windowInSecondary->assertNoEvents();
3627
3628 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003629 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003630 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003631 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003632 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003633
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003634 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003635 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003636
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003637 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003638 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3639 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003640
3641 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003642 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003643 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003644 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003645 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003646 windowInSecondary->assertNoEvents();
3647}
3648
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003649// Test per-display input monitors for motion event.
3650TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003651 FakeMonitorReceiver monitorInPrimary =
3652 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3653 FakeMonitorReceiver monitorInSecondary =
3654 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003655
3656 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003657 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3658 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3659 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003660 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003661 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003662 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003663 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003664
3665 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003666 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3667 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3668 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003669 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003670 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003671 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003672 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003673
3674 // Test inject a non-pointer motion event.
3675 // If specific a display, it will dispatch to the focused window of particular display,
3676 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003677 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3678 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3679 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003680 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003681 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003682 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003683 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003684}
3685
3686// Test per-display input monitors for key event.
3687TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003688 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003689 FakeMonitorReceiver monitorInPrimary =
3690 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3691 FakeMonitorReceiver monitorInSecondary =
3692 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003693
3694 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003695 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3696 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003697 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003698 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003699 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003700 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003701}
3702
Vishnu Nair958da932020-08-21 17:12:37 -07003703TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3704 sp<FakeWindowHandle> secondWindowInPrimary =
3705 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3706 secondWindowInPrimary->setFocusable(true);
3707 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3708 setFocusedWindow(secondWindowInPrimary);
3709 windowInPrimary->consumeFocusEvent(false);
3710 secondWindowInPrimary->consumeFocusEvent(true);
3711
3712 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003713 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3714 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003715 windowInPrimary->assertNoEvents();
3716 windowInSecondary->assertNoEvents();
3717 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3718}
3719
Arthur Hungdfd528e2021-12-08 13:23:04 +00003720TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3721 FakeMonitorReceiver monitorInPrimary =
3722 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3723 FakeMonitorReceiver monitorInSecondary =
3724 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3725
3726 // Test touch down on primary display.
3727 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3728 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3729 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3730 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3731 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3732
3733 // Test touch down on second display.
3734 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3735 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3736 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3737 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3738 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3739
3740 // Trigger cancel touch.
3741 mDispatcher->cancelCurrentTouch();
3742 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3743 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3744 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3745 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3746
3747 // Test inject a move motion event, no window/monitor should receive the event.
3748 ASSERT_EQ(InputEventInjectionResult::FAILED,
3749 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3750 ADISPLAY_ID_DEFAULT, {110, 200}))
3751 << "Inject motion event should return InputEventInjectionResult::FAILED";
3752 windowInPrimary->assertNoEvents();
3753 monitorInPrimary.assertNoEvents();
3754
3755 ASSERT_EQ(InputEventInjectionResult::FAILED,
3756 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3757 SECOND_DISPLAY_ID, {110, 200}))
3758 << "Inject motion event should return InputEventInjectionResult::FAILED";
3759 windowInSecondary->assertNoEvents();
3760 monitorInSecondary.assertNoEvents();
3761}
3762
Jackal Guof9696682018-10-05 12:23:23 +08003763class InputFilterTest : public InputDispatcherTest {
3764protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003765 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3766 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003767 NotifyMotionArgs motionArgs;
3768
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003769 motionArgs =
3770 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003771 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003772 motionArgs =
3773 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003774 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003775 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003776 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003777 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3778 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003779 } else {
3780 mFakePolicy->assertFilterInputEventWasNotCalled();
3781 }
3782 }
3783
3784 void testNotifyKey(bool expectToBeFiltered) {
3785 NotifyKeyArgs keyArgs;
3786
3787 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3788 mDispatcher->notifyKey(&keyArgs);
3789 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3790 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003791 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003792
3793 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003794 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003795 } else {
3796 mFakePolicy->assertFilterInputEventWasNotCalled();
3797 }
3798 }
3799};
3800
3801// Test InputFilter for MotionEvent
3802TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3803 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3804 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3805 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3806
3807 // Enable InputFilter
3808 mDispatcher->setInputFilterEnabled(true);
3809 // Test touch on both primary and second display, and check if both events are filtered.
3810 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3811 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3812
3813 // Disable InputFilter
3814 mDispatcher->setInputFilterEnabled(false);
3815 // Test touch on both primary and second display, and check if both events aren't filtered.
3816 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3817 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3818}
3819
3820// Test InputFilter for KeyEvent
3821TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3822 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3823 testNotifyKey(/*expectToBeFiltered*/ false);
3824
3825 // Enable InputFilter
3826 mDispatcher->setInputFilterEnabled(true);
3827 // Send a key event, and check if it is filtered.
3828 testNotifyKey(/*expectToBeFiltered*/ true);
3829
3830 // Disable InputFilter
3831 mDispatcher->setInputFilterEnabled(false);
3832 // Send a key event, and check if it isn't filtered.
3833 testNotifyKey(/*expectToBeFiltered*/ false);
3834}
3835
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003836// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3837// logical display coordinate space.
3838TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3839 ui::Transform firstDisplayTransform;
3840 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3841 ui::Transform secondDisplayTransform;
3842 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3843
3844 std::vector<gui::DisplayInfo> displayInfos(2);
3845 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3846 displayInfos[0].transform = firstDisplayTransform;
3847 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3848 displayInfos[1].transform = secondDisplayTransform;
3849
3850 mDispatcher->onWindowInfosChanged({}, displayInfos);
3851
3852 // Enable InputFilter
3853 mDispatcher->setInputFilterEnabled(true);
3854
3855 // Ensure the correct transforms are used for the displays.
3856 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3857 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3858}
3859
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003860class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3861protected:
3862 virtual void SetUp() override {
3863 InputDispatcherTest::SetUp();
3864
3865 /**
3866 * We don't need to enable input filter to test the injected event policy, but we enabled it
3867 * here to make the tests more realistic, since this policy only matters when inputfilter is
3868 * on.
3869 */
3870 mDispatcher->setInputFilterEnabled(true);
3871
3872 std::shared_ptr<InputApplicationHandle> application =
3873 std::make_shared<FakeApplicationHandle>();
3874 mWindow =
3875 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3876
3877 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3878 mWindow->setFocusable(true);
3879 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3880 setFocusedWindow(mWindow);
3881 mWindow->consumeFocusEvent(true);
3882 }
3883
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003884 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3885 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003886 KeyEvent event;
3887
3888 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3889 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3890 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3891 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3892 const int32_t additionalPolicyFlags =
3893 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3894 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3895 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3896 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3897 policyFlags | additionalPolicyFlags));
3898
3899 InputEvent* received = mWindow->consume();
3900 ASSERT_NE(nullptr, received);
3901 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003902 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3903 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3904 ASSERT_EQ(flags, keyEvent.getFlags());
3905 }
3906
3907 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3908 int32_t flags) {
3909 MotionEvent event;
3910 PointerProperties pointerProperties[1];
3911 PointerCoords pointerCoords[1];
3912 pointerProperties[0].clear();
3913 pointerProperties[0].id = 0;
3914 pointerCoords[0].clear();
3915 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3916 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3917
3918 ui::Transform identityTransform;
3919 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3920 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3921 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3922 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3923 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003924 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003925 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003926 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3927
3928 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3929 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3930 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3931 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3932 policyFlags | additionalPolicyFlags));
3933
3934 InputEvent* received = mWindow->consume();
3935 ASSERT_NE(nullptr, received);
3936 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3937 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3938 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3939 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003940 }
3941
3942private:
3943 sp<FakeWindowHandle> mWindow;
3944};
3945
3946TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003947 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3948 // filter. Without it, the event will no different from a regularly injected event, and the
3949 // injected device id will be overwritten.
3950 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3951 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003952}
3953
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003954TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003955 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003956 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3957 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3958}
3959
3960TEST_F(InputFilterInjectionPolicyTest,
3961 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3962 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3963 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3964 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003965}
3966
3967TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3968 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003969 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003970}
3971
chaviwfd6d3512019-03-25 13:23:49 -07003972class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003973 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003974 InputDispatcherTest::SetUp();
3975
Chris Yea209fde2020-07-22 13:54:51 -07003976 std::shared_ptr<FakeApplicationHandle> application =
3977 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003978 mUnfocusedWindow =
3979 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003980 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3981 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3982 // window.
chaviw3277faf2021-05-19 16:45:23 -05003983 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003984
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003985 mFocusedWindow =
3986 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3987 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05003988 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003989
3990 // Set focused application.
3991 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003992 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003993
3994 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003995 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003996 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003997 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003998 }
3999
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004000 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004001 InputDispatcherTest::TearDown();
4002
4003 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004004 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004005 }
4006
4007protected:
4008 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004009 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004010 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004011};
4012
4013// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4014// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4015// the onPointerDownOutsideFocus callback.
4016TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004017 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004018 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4019 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004020 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004021 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004022
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004023 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004024 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4025}
4026
4027// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4028// DOWN on the window that doesn't have focus. Ensure no window received the
4029// onPointerDownOutsideFocus callback.
4030TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004031 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004032 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004033 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004034 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004035
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004036 ASSERT_TRUE(mDispatcher->waitForIdle());
4037 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004038}
4039
4040// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4041// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4042TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004043 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4044 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004045 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004046 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004047
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004048 ASSERT_TRUE(mDispatcher->waitForIdle());
4049 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004050}
4051
4052// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4053// DOWN on the window that already has focus. Ensure no window received the
4054// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004055TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004056 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004057 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004058 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004059 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004060 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004061
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004062 ASSERT_TRUE(mDispatcher->waitForIdle());
4063 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004064}
4065
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004066// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4067// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4068TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4069 const MotionEvent event =
4070 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4071 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4072 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4073 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4074 .build();
4075 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4076 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4077 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4078
4079 ASSERT_TRUE(mDispatcher->waitForIdle());
4080 mFakePolicy->assertOnPointerDownWasNotCalled();
4081 // Ensure that the unfocused window did not receive any FOCUS events.
4082 mUnfocusedWindow->assertNoEvents();
4083}
4084
chaviwaf87b3e2019-10-01 16:59:28 -07004085// These tests ensures we can send touch events to a single client when there are multiple input
4086// windows that point to the same client token.
4087class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4088 virtual void SetUp() override {
4089 InputDispatcherTest::SetUp();
4090
Chris Yea209fde2020-07-22 13:54:51 -07004091 std::shared_ptr<FakeApplicationHandle> application =
4092 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004093 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4094 ADISPLAY_ID_DEFAULT);
4095 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
4096 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05004097 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004098 mWindow1->setFrame(Rect(0, 0, 100, 100));
4099
4100 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4101 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05004102 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004103 mWindow2->setFrame(Rect(100, 100, 200, 200));
4104
Arthur Hung72d8dc32020-03-28 00:48:39 +00004105 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004106 }
4107
4108protected:
4109 sp<FakeWindowHandle> mWindow1;
4110 sp<FakeWindowHandle> mWindow2;
4111
4112 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004113 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004114 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4115 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004116 }
4117
4118 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4119 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004120 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004121 InputEvent* event = window->consume();
4122
4123 ASSERT_NE(nullptr, event) << name.c_str()
4124 << ": consumer should have returned non-NULL event.";
4125
4126 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4127 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4128 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4129
4130 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004131 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004132
4133 for (size_t i = 0; i < points.size(); i++) {
4134 float expectedX = points[i].x;
4135 float expectedY = points[i].y;
4136
4137 EXPECT_EQ(expectedX, motionEvent.getX(i))
4138 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4139 << ", got " << motionEvent.getX(i);
4140 EXPECT_EQ(expectedY, motionEvent.getY(i))
4141 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4142 << ", got " << motionEvent.getY(i);
4143 }
4144 }
chaviw9eaa22c2020-07-01 16:21:27 -07004145
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004146 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004147 std::vector<PointF> expectedPoints) {
4148 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4149 ADISPLAY_ID_DEFAULT, touchedPoints);
4150 mDispatcher->notifyMotion(&motionArgs);
4151
4152 // Always consume from window1 since it's the window that has the InputReceiver
4153 consumeMotionEvent(mWindow1, action, expectedPoints);
4154 }
chaviwaf87b3e2019-10-01 16:59:28 -07004155};
4156
4157TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4158 // Touch Window 1
4159 PointF touchedPoint = {10, 10};
4160 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004161 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004162
4163 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004164 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004165
4166 // Touch Window 2
4167 touchedPoint = {150, 150};
4168 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004169 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004170}
4171
chaviw9eaa22c2020-07-01 16:21:27 -07004172TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4173 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004174 mWindow2->setWindowScale(0.5f, 0.5f);
4175
4176 // Touch Window 1
4177 PointF touchedPoint = {10, 10};
4178 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004179 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004180 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004181 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004182
4183 // Touch Window 2
4184 touchedPoint = {150, 150};
4185 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004186 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4187 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004188
chaviw9eaa22c2020-07-01 16:21:27 -07004189 // Update the transform so rotation is set
4190 mWindow2->setWindowTransform(0, -1, 1, 0);
4191 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4192 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004193}
4194
chaviw9eaa22c2020-07-01 16:21:27 -07004195TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004196 mWindow2->setWindowScale(0.5f, 0.5f);
4197
4198 // Touch Window 1
4199 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4200 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004201 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004202
4203 // Touch Window 2
4204 int32_t actionPointerDown =
4205 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004206 touchedPoints.push_back(PointF{150, 150});
4207 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4208 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004209
chaviw9eaa22c2020-07-01 16:21:27 -07004210 // Release Window 2
4211 int32_t actionPointerUp =
4212 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4213 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4214 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004215
chaviw9eaa22c2020-07-01 16:21:27 -07004216 // Update the transform so rotation is set for Window 2
4217 mWindow2->setWindowTransform(0, -1, 1, 0);
4218 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4219 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004220}
4221
chaviw9eaa22c2020-07-01 16:21:27 -07004222TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004223 mWindow2->setWindowScale(0.5f, 0.5f);
4224
4225 // Touch Window 1
4226 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4227 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004228 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004229
4230 // Touch Window 2
4231 int32_t actionPointerDown =
4232 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004233 touchedPoints.push_back(PointF{150, 150});
4234 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004235
chaviw9eaa22c2020-07-01 16:21:27 -07004236 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004237
4238 // Move both windows
4239 touchedPoints = {{20, 20}, {175, 175}};
4240 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4241 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4242
chaviw9eaa22c2020-07-01 16:21:27 -07004243 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004244
chaviw9eaa22c2020-07-01 16:21:27 -07004245 // Release Window 2
4246 int32_t actionPointerUp =
4247 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4248 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4249 expectedPoints.pop_back();
4250
4251 // Touch Window 2
4252 mWindow2->setWindowTransform(0, -1, 1, 0);
4253 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4254 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4255
4256 // Move both windows
4257 touchedPoints = {{20, 20}, {175, 175}};
4258 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4259 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4260
4261 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004262}
4263
4264TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4265 mWindow1->setWindowScale(0.5f, 0.5f);
4266
4267 // Touch Window 1
4268 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4269 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004270 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004271
4272 // Touch Window 2
4273 int32_t actionPointerDown =
4274 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004275 touchedPoints.push_back(PointF{150, 150});
4276 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004277
chaviw9eaa22c2020-07-01 16:21:27 -07004278 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004279
4280 // Move both windows
4281 touchedPoints = {{20, 20}, {175, 175}};
4282 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4283 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4284
chaviw9eaa22c2020-07-01 16:21:27 -07004285 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004286}
4287
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004288class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4289 virtual void SetUp() override {
4290 InputDispatcherTest::SetUp();
4291
Chris Yea209fde2020-07-22 13:54:51 -07004292 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004293 mApplication->setDispatchingTimeout(20ms);
4294 mWindow =
4295 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4296 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004297 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004298 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004299 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4300 // window.
chaviw3277faf2021-05-19 16:45:23 -05004301 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004302
4303 // Set focused application.
4304 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4305
4306 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004307 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004308 mWindow->consumeFocusEvent(true);
4309 }
4310
4311 virtual void TearDown() override {
4312 InputDispatcherTest::TearDown();
4313 mWindow.clear();
4314 }
4315
4316protected:
Chris Yea209fde2020-07-22 13:54:51 -07004317 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004318 sp<FakeWindowHandle> mWindow;
4319 static constexpr PointF WINDOW_LOCATION = {20, 20};
4320
4321 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004322 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004323 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4324 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004325 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004326 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4327 WINDOW_LOCATION));
4328 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004329
4330 sp<FakeWindowHandle> addSpyWindow() {
4331 sp<FakeWindowHandle> spy =
4332 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4333 spy->setTrustedOverlay(true);
4334 spy->setFocusable(false);
4335 spy->setInputFeatures(WindowInfo::Feature::SPY);
4336 spy->setDispatchingTimeout(30ms);
4337 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4338 return spy;
4339 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004340};
4341
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004342// Send a tap and respond, which should not cause an ANR.
4343TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4344 tapOnWindow();
4345 mWindow->consumeMotionDown();
4346 mWindow->consumeMotionUp();
4347 ASSERT_TRUE(mDispatcher->waitForIdle());
4348 mFakePolicy->assertNotifyAnrWasNotCalled();
4349}
4350
4351// Send a regular key and respond, which should not cause an ANR.
4352TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004353 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004354 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4355 ASSERT_TRUE(mDispatcher->waitForIdle());
4356 mFakePolicy->assertNotifyAnrWasNotCalled();
4357}
4358
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004359TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4360 mWindow->setFocusable(false);
4361 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4362 mWindow->consumeFocusEvent(false);
4363
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004364 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004365 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004366 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4367 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004368 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004369 // Key will not go to window because we have no focused window.
4370 // The 'no focused window' ANR timer should start instead.
4371
4372 // Now, the focused application goes away.
4373 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4374 // The key should get dropped and there should be no ANR.
4375
4376 ASSERT_TRUE(mDispatcher->waitForIdle());
4377 mFakePolicy->assertNotifyAnrWasNotCalled();
4378}
4379
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004380// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004381// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4382// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004383TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004384 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004385 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4386 WINDOW_LOCATION));
4387
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004388 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4389 ASSERT_TRUE(sequenceNum);
4390 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004391 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004392
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004393 mWindow->finishEvent(*sequenceNum);
4394 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4395 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004396 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004397 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004398}
4399
4400// Send a key to the app and have the app not respond right away.
4401TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4402 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004403 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004404 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4405 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004406 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004407 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004408 ASSERT_TRUE(mDispatcher->waitForIdle());
4409}
4410
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004411// We have a focused application, but no focused window
4412TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004413 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004414 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4415 mWindow->consumeFocusEvent(false);
4416
4417 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004418 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004419 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4420 WINDOW_LOCATION));
4421 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4422 mDispatcher->waitForIdle();
4423 mFakePolicy->assertNotifyAnrWasNotCalled();
4424
4425 // Once a focused event arrives, we get an ANR for this application
4426 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4427 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004428 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004429 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004430 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004431 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004432 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004433 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004434 ASSERT_TRUE(mDispatcher->waitForIdle());
4435}
4436
4437// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004438// Make sure that we don't notify policy twice about the same ANR.
4439TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004440 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004441 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4442 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004443
4444 // Once a focused event arrives, we get an ANR for this application
4445 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4446 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004447 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004448 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004449 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004450 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004451 const std::chrono::duration appTimeout =
4452 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004453 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004454
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004455 std::this_thread::sleep_for(appTimeout);
4456 // ANR should not be raised again. It is up to policy to do that if it desires.
4457 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004458
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004459 // If we now get a focused window, the ANR should stop, but the policy handles that via
4460 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004461 ASSERT_TRUE(mDispatcher->waitForIdle());
4462}
4463
4464// We have a focused application, but no focused window
4465TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004466 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004467 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4468 mWindow->consumeFocusEvent(false);
4469
4470 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004471 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004472 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004473 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4474 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004475
4476 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004477 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004478
4479 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004480 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004481 ASSERT_TRUE(mDispatcher->waitForIdle());
4482 mWindow->assertNoEvents();
4483}
4484
4485/**
4486 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4487 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4488 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4489 * the ANR mechanism should still work.
4490 *
4491 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4492 * DOWN event, while not responding on the second one.
4493 */
4494TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4495 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4496 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4497 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4498 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4499 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004500 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004501
4502 // Now send ACTION_UP, with identical timestamp
4503 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4504 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4505 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4506 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004507 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004508
4509 // We have now sent down and up. Let's consume first event and then ANR on the second.
4510 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4511 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004512 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004513}
4514
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004515// A spy window can receive an ANR
4516TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4517 sp<FakeWindowHandle> spy = addSpyWindow();
4518
4519 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4520 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4521 WINDOW_LOCATION));
4522 mWindow->consumeMotionDown();
4523
4524 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4525 ASSERT_TRUE(sequenceNum);
4526 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4527 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy->getToken());
4528
4529 spy->finishEvent(*sequenceNum);
4530 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4531 0 /*flags*/);
4532 ASSERT_TRUE(mDispatcher->waitForIdle());
4533 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken());
4534}
4535
4536// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004537// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004538TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4539 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004540
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004541 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4542 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004543 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004544 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004545
4546 // Stuck on the ACTION_UP
4547 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004548 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004549
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004550 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004551 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004552 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4553 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004554
4555 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4556 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004557 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004558 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004559 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004560}
4561
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004562// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004563// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004564TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4565 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004566
4567 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004568 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4569 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004570
4571 mWindow->consumeMotionDown();
4572 // Stuck on the ACTION_UP
4573 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004574 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004575
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004576 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004577 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004578 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4579 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004580
4581 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4582 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004583 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004584 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004585 spy->assertNoEvents();
4586}
4587
4588TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4589 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4590
4591 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4592
4593 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4594 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4595 WINDOW_LOCATION));
4596
4597 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4598 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4599 ASSERT_TRUE(consumeSeq);
4600
4601 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(30ms);
4602
4603 monitor.finishEvent(*consumeSeq);
4604 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4605
4606 ASSERT_TRUE(mDispatcher->waitForIdle());
4607 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004608}
4609
4610// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4611// process events, you don't get an anr. When the window later becomes unresponsive again, you
4612// get an ANR again.
4613// 1. tap -> block on ACTION_UP -> receive ANR
4614// 2. consume all pending events (= queue becomes healthy again)
4615// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4616TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4617 tapOnWindow();
4618
4619 mWindow->consumeMotionDown();
4620 // Block on ACTION_UP
4621 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004622 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004623 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4624 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004625 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004626 mWindow->assertNoEvents();
4627
4628 tapOnWindow();
4629 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004630 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004631 mWindow->consumeMotionUp();
4632
4633 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004634 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004635 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004636 mWindow->assertNoEvents();
4637}
4638
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004639// If a connection remains unresponsive for a while, make sure policy is only notified once about
4640// it.
4641TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004642 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004643 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4644 WINDOW_LOCATION));
4645
4646 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004647 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004648 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004649 // 'notifyConnectionUnresponsive' should only be called once per connection
4650 mFakePolicy->assertNotifyAnrWasNotCalled();
4651 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004652 mWindow->consumeMotionDown();
4653 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4654 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4655 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004656 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004657 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004658 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004659}
4660
4661/**
4662 * If a window is processing a motion event, and then a key event comes in, the key event should
4663 * not to to the focused window until the motion is processed.
4664 *
4665 * Warning!!!
4666 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4667 * and the injection timeout that we specify when injecting the key.
4668 * We must have the injection timeout (10ms) be smaller than
4669 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4670 *
4671 * If that value changes, this test should also change.
4672 */
4673TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4674 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4675 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4676
4677 tapOnWindow();
4678 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4679 ASSERT_TRUE(downSequenceNum);
4680 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4681 ASSERT_TRUE(upSequenceNum);
4682 // Don't finish the events yet, and send a key
4683 // Injection will "succeed" because we will eventually give up and send the key to the focused
4684 // window even if motions are still being processed. But because the injection timeout is short,
4685 // we will receive INJECTION_TIMED_OUT as the result.
4686
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004687 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004688 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004689 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4690 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004691 // Key will not be sent to the window, yet, because the window is still processing events
4692 // and the key remains pending, waiting for the touch events to be processed
4693 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4694 ASSERT_FALSE(keySequenceNum);
4695
4696 std::this_thread::sleep_for(500ms);
4697 // if we wait long enough though, dispatcher will give up, and still send the key
4698 // to the focused window, even though we have not yet finished the motion event
4699 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4700 mWindow->finishEvent(*downSequenceNum);
4701 mWindow->finishEvent(*upSequenceNum);
4702}
4703
4704/**
4705 * If a window is processing a motion event, and then a key event comes in, the key event should
4706 * not go to the focused window until the motion is processed.
4707 * If then a new motion comes in, then the pending key event should be going to the currently
4708 * focused window right away.
4709 */
4710TEST_F(InputDispatcherSingleWindowAnr,
4711 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4712 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4713 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4714
4715 tapOnWindow();
4716 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4717 ASSERT_TRUE(downSequenceNum);
4718 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4719 ASSERT_TRUE(upSequenceNum);
4720 // Don't finish the events yet, and send a key
4721 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004722 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004723 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004724 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004725 // At this point, key is still pending, and should not be sent to the application yet.
4726 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4727 ASSERT_FALSE(keySequenceNum);
4728
4729 // Now tap down again. It should cause the pending key to go to the focused window right away.
4730 tapOnWindow();
4731 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4732 // the other events yet. We can finish events in any order.
4733 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4734 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4735 mWindow->consumeMotionDown();
4736 mWindow->consumeMotionUp();
4737 mWindow->assertNoEvents();
4738}
4739
4740class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4741 virtual void SetUp() override {
4742 InputDispatcherTest::SetUp();
4743
Chris Yea209fde2020-07-22 13:54:51 -07004744 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004745 mApplication->setDispatchingTimeout(10ms);
4746 mUnfocusedWindow =
4747 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4748 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4749 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4750 // window.
4751 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004752 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4753 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4754 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004755
4756 mFocusedWindow =
4757 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004758 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004759 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004760 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004761
4762 // Set focused application.
4763 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004764 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004765
4766 // Expect one focus window exist in display.
4767 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004768 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004769 mFocusedWindow->consumeFocusEvent(true);
4770 }
4771
4772 virtual void TearDown() override {
4773 InputDispatcherTest::TearDown();
4774
4775 mUnfocusedWindow.clear();
4776 mFocusedWindow.clear();
4777 }
4778
4779protected:
Chris Yea209fde2020-07-22 13:54:51 -07004780 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004781 sp<FakeWindowHandle> mUnfocusedWindow;
4782 sp<FakeWindowHandle> mFocusedWindow;
4783 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4784 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4785 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4786
4787 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4788
4789 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4790
4791private:
4792 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004793 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004794 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4795 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004796 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004797 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4798 location));
4799 }
4800};
4801
4802// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4803// should be ANR'd first.
4804TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004805 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004806 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4807 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004808 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004809 mFocusedWindow->consumeMotionDown();
4810 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4811 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4812 // We consumed all events, so no ANR
4813 ASSERT_TRUE(mDispatcher->waitForIdle());
4814 mFakePolicy->assertNotifyAnrWasNotCalled();
4815
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004816 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004817 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4818 FOCUSED_WINDOW_LOCATION));
4819 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4820 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004821
4822 const std::chrono::duration timeout =
4823 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004824 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004825 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4826 // sequence to make it consistent
4827 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004828 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004829 mFocusedWindow->consumeMotionDown();
4830 // This cancel is generated because the connection was unresponsive
4831 mFocusedWindow->consumeMotionCancel();
4832 mFocusedWindow->assertNoEvents();
4833 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004834 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004835 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004836 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004837}
4838
4839// If we have 2 windows with identical timeouts that are both unresponsive,
4840// it doesn't matter which order they should have ANR.
4841// But we should receive ANR for both.
4842TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4843 // Set the timeout for unfocused window to match the focused window
4844 mUnfocusedWindow->setDispatchingTimeout(10ms);
4845 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4846
4847 tapOnFocusedWindow();
4848 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004849 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4850 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004851
4852 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004853 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4854 mFocusedWindow->getToken() == anrConnectionToken2);
4855 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4856 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004857
4858 ASSERT_TRUE(mDispatcher->waitForIdle());
4859 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004860
4861 mFocusedWindow->consumeMotionDown();
4862 mFocusedWindow->consumeMotionUp();
4863 mUnfocusedWindow->consumeMotionOutside();
4864
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004865 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4866 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004867
4868 // Both applications should be marked as responsive, in any order
4869 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4870 mFocusedWindow->getToken() == responsiveToken2);
4871 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4872 mUnfocusedWindow->getToken() == responsiveToken2);
4873 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004874}
4875
4876// If a window is already not responding, the second tap on the same window should be ignored.
4877// We should also log an error to account for the dropped event (not tested here).
4878// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4879TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4880 tapOnFocusedWindow();
4881 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4882 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4883 // Receive the events, but don't respond
4884 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4885 ASSERT_TRUE(downEventSequenceNum);
4886 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4887 ASSERT_TRUE(upEventSequenceNum);
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 Vishniakoud44dddf2020-03-25 16:16:40 -07004891
4892 // Tap once again
4893 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004894 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004895 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4896 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004897 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004898 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4899 FOCUSED_WINDOW_LOCATION));
4900 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4901 // valid touch target
4902 mUnfocusedWindow->assertNoEvents();
4903
4904 // Consume the first tap
4905 mFocusedWindow->finishEvent(*downEventSequenceNum);
4906 mFocusedWindow->finishEvent(*upEventSequenceNum);
4907 ASSERT_TRUE(mDispatcher->waitForIdle());
4908 // The second tap did not go to the focused window
4909 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004910 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004911 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004912 mFakePolicy->assertNotifyAnrWasNotCalled();
4913}
4914
4915// If you tap outside of all windows, there will not be ANR
4916TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004917 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004918 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4919 LOCATION_OUTSIDE_ALL_WINDOWS));
4920 ASSERT_TRUE(mDispatcher->waitForIdle());
4921 mFakePolicy->assertNotifyAnrWasNotCalled();
4922}
4923
4924// Since the focused window is paused, tapping on it should not produce any events
4925TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4926 mFocusedWindow->setPaused(true);
4927 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4928
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004929 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004930 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4931 FOCUSED_WINDOW_LOCATION));
4932
4933 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4934 ASSERT_TRUE(mDispatcher->waitForIdle());
4935 // Should not ANR because the window is paused, and touches shouldn't go to it
4936 mFakePolicy->assertNotifyAnrWasNotCalled();
4937
4938 mFocusedWindow->assertNoEvents();
4939 mUnfocusedWindow->assertNoEvents();
4940}
4941
4942/**
4943 * If a window is processing a motion event, and then a key event comes in, the key event should
4944 * not to to the focused window until the motion is processed.
4945 * If a different window becomes focused at this time, the key should go to that window instead.
4946 *
4947 * Warning!!!
4948 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4949 * and the injection timeout that we specify when injecting the key.
4950 * We must have the injection timeout (10ms) be smaller than
4951 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4952 *
4953 * If that value changes, this test should also change.
4954 */
4955TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4956 // Set a long ANR timeout to prevent it from triggering
4957 mFocusedWindow->setDispatchingTimeout(2s);
4958 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4959
4960 tapOnUnfocusedWindow();
4961 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4962 ASSERT_TRUE(downSequenceNum);
4963 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4964 ASSERT_TRUE(upSequenceNum);
4965 // Don't finish the events yet, and send a key
4966 // Injection will succeed because we will eventually give up and send the key to the focused
4967 // window even if motions are still being processed.
4968
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004969 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004970 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004971 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4972 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004973 // Key will not be sent to the window, yet, because the window is still processing events
4974 // and the key remains pending, waiting for the touch events to be processed
4975 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4976 ASSERT_FALSE(keySequenceNum);
4977
4978 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004979 mFocusedWindow->setFocusable(false);
4980 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004981 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004982 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004983
4984 // Focus events should precede the key events
4985 mUnfocusedWindow->consumeFocusEvent(true);
4986 mFocusedWindow->consumeFocusEvent(false);
4987
4988 // Finish the tap events, which should unblock dispatcher
4989 mUnfocusedWindow->finishEvent(*downSequenceNum);
4990 mUnfocusedWindow->finishEvent(*upSequenceNum);
4991
4992 // Now that all queues are cleared and no backlog in the connections, the key event
4993 // can finally go to the newly focused "mUnfocusedWindow".
4994 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4995 mFocusedWindow->assertNoEvents();
4996 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004997 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004998}
4999
5000// When the touch stream is split across 2 windows, and one of them does not respond,
5001// then ANR should be raised and the touch should be canceled for the unresponsive window.
5002// The other window should not be affected by that.
5003TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5004 // Touch Window 1
5005 NotifyMotionArgs motionArgs =
5006 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5007 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5008 mDispatcher->notifyMotion(&motionArgs);
5009 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5010 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5011
5012 // Touch Window 2
5013 int32_t actionPointerDown =
5014 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
5015
5016 motionArgs =
5017 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5018 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
5019 mDispatcher->notifyMotion(&motionArgs);
5020
5021 const std::chrono::duration timeout =
5022 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005023 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005024
5025 mUnfocusedWindow->consumeMotionDown();
5026 mFocusedWindow->consumeMotionDown();
5027 // Focused window may or may not receive ACTION_MOVE
5028 // But it should definitely receive ACTION_CANCEL due to the ANR
5029 InputEvent* event;
5030 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5031 ASSERT_TRUE(moveOrCancelSequenceNum);
5032 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5033 ASSERT_NE(nullptr, event);
5034 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5035 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5036 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5037 mFocusedWindow->consumeMotionCancel();
5038 } else {
5039 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5040 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005041 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005042 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005043
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005044 mUnfocusedWindow->assertNoEvents();
5045 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005046 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005047}
5048
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005049/**
5050 * If we have no focused window, and a key comes in, we start the ANR timer.
5051 * The focused application should add a focused window before the timer runs out to prevent ANR.
5052 *
5053 * If the user touches another application during this time, the key should be dropped.
5054 * Next, if a new focused window comes in, without toggling the focused application,
5055 * then no ANR should occur.
5056 *
5057 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5058 * but in some cases the policy may not update the focused application.
5059 */
5060TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5061 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5062 std::make_shared<FakeApplicationHandle>();
5063 focusedApplication->setDispatchingTimeout(60ms);
5064 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5065 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5066 mFocusedWindow->setFocusable(false);
5067
5068 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5069 mFocusedWindow->consumeFocusEvent(false);
5070
5071 // Send a key. The ANR timer should start because there is no focused window.
5072 // 'focusedApplication' will get blamed if this timer completes.
5073 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005074 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005075 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005076 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5077 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005078 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005079
5080 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5081 // then the injected touches won't cause the focused event to get dropped.
5082 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5083 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5084 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5085 // For this test, it means that the key would get delivered to the window once it becomes
5086 // focused.
5087 std::this_thread::sleep_for(10ms);
5088
5089 // Touch unfocused window. This should force the pending key to get dropped.
5090 NotifyMotionArgs motionArgs =
5091 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5092 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5093 mDispatcher->notifyMotion(&motionArgs);
5094
5095 // We do not consume the motion right away, because that would require dispatcher to first
5096 // process (== drop) the key event, and by that time, ANR will be raised.
5097 // Set the focused window first.
5098 mFocusedWindow->setFocusable(true);
5099 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5100 setFocusedWindow(mFocusedWindow);
5101 mFocusedWindow->consumeFocusEvent(true);
5102 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5103 // to another application. This could be a bug / behaviour in the policy.
5104
5105 mUnfocusedWindow->consumeMotionDown();
5106
5107 ASSERT_TRUE(mDispatcher->waitForIdle());
5108 // Should not ANR because we actually have a focused window. It was just added too slowly.
5109 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5110}
5111
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005112// These tests ensure we cannot send touch events to a window that's positioned behind a window
5113// that has feature NO_INPUT_CHANNEL.
5114// Layout:
5115// Top (closest to user)
5116// mNoInputWindow (above all windows)
5117// mBottomWindow
5118// Bottom (furthest from user)
5119class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5120 virtual void SetUp() override {
5121 InputDispatcherTest::SetUp();
5122
5123 mApplication = std::make_shared<FakeApplicationHandle>();
5124 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5125 "Window without input channel", ADISPLAY_ID_DEFAULT,
5126 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5127
chaviw3277faf2021-05-19 16:45:23 -05005128 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005129 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5130 // It's perfectly valid for this window to not have an associated input channel
5131
5132 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5133 ADISPLAY_ID_DEFAULT);
5134 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5135
5136 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5137 }
5138
5139protected:
5140 std::shared_ptr<FakeApplicationHandle> mApplication;
5141 sp<FakeWindowHandle> mNoInputWindow;
5142 sp<FakeWindowHandle> mBottomWindow;
5143};
5144
5145TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5146 PointF touchedPoint = {10, 10};
5147
5148 NotifyMotionArgs motionArgs =
5149 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5150 ADISPLAY_ID_DEFAULT, {touchedPoint});
5151 mDispatcher->notifyMotion(&motionArgs);
5152
5153 mNoInputWindow->assertNoEvents();
5154 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5155 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5156 // and therefore should prevent mBottomWindow from receiving touches
5157 mBottomWindow->assertNoEvents();
5158}
5159
5160/**
5161 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5162 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5163 */
5164TEST_F(InputDispatcherMultiWindowOcclusionTests,
5165 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5166 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5167 "Window with input channel and NO_INPUT_CHANNEL",
5168 ADISPLAY_ID_DEFAULT);
5169
chaviw3277faf2021-05-19 16:45:23 -05005170 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005171 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5172 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5173
5174 PointF touchedPoint = {10, 10};
5175
5176 NotifyMotionArgs motionArgs =
5177 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5178 ADISPLAY_ID_DEFAULT, {touchedPoint});
5179 mDispatcher->notifyMotion(&motionArgs);
5180
5181 mNoInputWindow->assertNoEvents();
5182 mBottomWindow->assertNoEvents();
5183}
5184
Vishnu Nair958da932020-08-21 17:12:37 -07005185class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5186protected:
5187 std::shared_ptr<FakeApplicationHandle> mApp;
5188 sp<FakeWindowHandle> mWindow;
5189 sp<FakeWindowHandle> mMirror;
5190
5191 virtual void SetUp() override {
5192 InputDispatcherTest::SetUp();
5193 mApp = std::make_shared<FakeApplicationHandle>();
5194 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5195 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5196 mWindow->getToken());
5197 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5198 mWindow->setFocusable(true);
5199 mMirror->setFocusable(true);
5200 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5201 }
5202};
5203
5204TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5205 // Request focus on a mirrored window
5206 setFocusedWindow(mMirror);
5207
5208 // window gets focused
5209 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005210 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5211 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005212 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5213}
5214
5215// A focused & mirrored window remains focused only if the window and its mirror are both
5216// focusable.
5217TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5218 setFocusedWindow(mMirror);
5219
5220 // window gets focused
5221 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005222 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5223 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005224 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005225 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5226 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005227 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5228
5229 mMirror->setFocusable(false);
5230 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5231
5232 // window loses focus since one of the windows associated with the token in not focusable
5233 mWindow->consumeFocusEvent(false);
5234
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005235 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5236 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005237 mWindow->assertNoEvents();
5238}
5239
5240// A focused & mirrored window remains focused until the window and its mirror both become
5241// invisible.
5242TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5243 setFocusedWindow(mMirror);
5244
5245 // window gets focused
5246 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005247 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5248 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005249 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005250 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5251 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005252 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5253
5254 mMirror->setVisible(false);
5255 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5256
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005257 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5258 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005259 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005260 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5261 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005262 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5263
5264 mWindow->setVisible(false);
5265 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5266
5267 // window loses focus only after all windows associated with the token become invisible.
5268 mWindow->consumeFocusEvent(false);
5269
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005270 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5271 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005272 mWindow->assertNoEvents();
5273}
5274
5275// A focused & mirrored window remains focused until both windows are removed.
5276TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5277 setFocusedWindow(mMirror);
5278
5279 // window gets focused
5280 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005281 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5282 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005283 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005284 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5285 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005286 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5287
5288 // single window is removed but the window token remains focused
5289 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5290
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005291 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5292 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005293 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005294 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5295 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005296 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5297
5298 // Both windows are removed
5299 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5300 mWindow->consumeFocusEvent(false);
5301
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005302 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5303 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005304 mWindow->assertNoEvents();
5305}
5306
5307// Focus request can be pending until one window becomes visible.
5308TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5309 // Request focus on an invisible mirror.
5310 mWindow->setVisible(false);
5311 mMirror->setVisible(false);
5312 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5313 setFocusedWindow(mMirror);
5314
5315 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005316 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005317 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005318 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005319
5320 mMirror->setVisible(true);
5321 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5322
5323 // window gets focused
5324 mWindow->consumeFocusEvent(true);
5325 // window gets the pending key event
5326 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5327}
Prabir Pradhan99987712020-11-10 18:43:05 -08005328
5329class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5330protected:
5331 std::shared_ptr<FakeApplicationHandle> mApp;
5332 sp<FakeWindowHandle> mWindow;
5333 sp<FakeWindowHandle> mSecondWindow;
5334
5335 void SetUp() override {
5336 InputDispatcherTest::SetUp();
5337 mApp = std::make_shared<FakeApplicationHandle>();
5338 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5339 mWindow->setFocusable(true);
5340 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5341 mSecondWindow->setFocusable(true);
5342
5343 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5344 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5345
5346 setFocusedWindow(mWindow);
5347 mWindow->consumeFocusEvent(true);
5348 }
5349
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005350 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5351 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005352 mDispatcher->notifyPointerCaptureChanged(&args);
5353 }
5354
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005355 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5356 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005357 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005358 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5359 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005360 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005361 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005362 }
5363};
5364
5365TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5366 // Ensure that capture cannot be obtained for unfocused windows.
5367 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5368 mFakePolicy->assertSetPointerCaptureNotCalled();
5369 mSecondWindow->assertNoEvents();
5370
5371 // Ensure that capture can be enabled from the focus window.
5372 requestAndVerifyPointerCapture(mWindow, true);
5373
5374 // Ensure that capture cannot be disabled from a window that does not have capture.
5375 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5376 mFakePolicy->assertSetPointerCaptureNotCalled();
5377
5378 // Ensure that capture can be disabled from the window with capture.
5379 requestAndVerifyPointerCapture(mWindow, false);
5380}
5381
5382TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005383 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005384
5385 setFocusedWindow(mSecondWindow);
5386
5387 // Ensure that the capture disabled event was sent first.
5388 mWindow->consumeCaptureEvent(false);
5389 mWindow->consumeFocusEvent(false);
5390 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005391 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005392
5393 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005394 notifyPointerCaptureChanged({});
5395 notifyPointerCaptureChanged(request);
5396 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005397 mWindow->assertNoEvents();
5398 mSecondWindow->assertNoEvents();
5399 mFakePolicy->assertSetPointerCaptureNotCalled();
5400}
5401
5402TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005403 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005404
5405 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005406 notifyPointerCaptureChanged({});
5407 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005408
5409 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005410 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005411 mWindow->consumeCaptureEvent(false);
5412 mWindow->assertNoEvents();
5413}
5414
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005415TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5416 requestAndVerifyPointerCapture(mWindow, true);
5417
5418 // The first window loses focus.
5419 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005420 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005421 mWindow->consumeCaptureEvent(false);
5422
5423 // Request Pointer Capture from the second window before the notification from InputReader
5424 // arrives.
5425 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005426 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005427
5428 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005429 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005430
5431 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005432 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005433
5434 mSecondWindow->consumeFocusEvent(true);
5435 mSecondWindow->consumeCaptureEvent(true);
5436}
5437
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005438TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5439 // App repeatedly enables and disables capture.
5440 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5441 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5442 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5443 mFakePolicy->assertSetPointerCaptureCalled(false);
5444 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5445 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5446
5447 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5448 // first request is now stale, this should do nothing.
5449 notifyPointerCaptureChanged(firstRequest);
5450 mWindow->assertNoEvents();
5451
5452 // InputReader notifies that the second request was enabled.
5453 notifyPointerCaptureChanged(secondRequest);
5454 mWindow->consumeCaptureEvent(true);
5455}
5456
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005457class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5458protected:
5459 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005460
5461 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5462 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5463
5464 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5465 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5466
5467 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5468 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5469 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5470 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5471 MAXIMUM_OBSCURING_OPACITY);
5472
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005473 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005474 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005475 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005476
5477 sp<FakeWindowHandle> mTouchWindow;
5478
5479 virtual void SetUp() override {
5480 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005481 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005482 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5483 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5484 }
5485
5486 virtual void TearDown() override {
5487 InputDispatcherTest::TearDown();
5488 mTouchWindow.clear();
5489 }
5490
chaviw3277faf2021-05-19 16:45:23 -05005491 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5492 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005493 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005494 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005495 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005496 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005497 return window;
5498 }
5499
5500 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5501 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5502 sp<FakeWindowHandle> window =
5503 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5504 // Generate an arbitrary PID based on the UID
5505 window->setOwnerInfo(1777 + (uid % 10000), uid);
5506 return window;
5507 }
5508
5509 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5510 NotifyMotionArgs args =
5511 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5512 ADISPLAY_ID_DEFAULT, points);
5513 mDispatcher->notifyMotion(&args);
5514 }
5515};
5516
5517TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005518 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005519 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005520 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005521
5522 touch();
5523
5524 mTouchWindow->assertNoEvents();
5525}
5526
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005527TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005528 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5529 const sp<FakeWindowHandle>& w =
5530 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5531 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5532
5533 touch();
5534
5535 mTouchWindow->assertNoEvents();
5536}
5537
5538TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005539 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5540 const sp<FakeWindowHandle>& w =
5541 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5542 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5543
5544 touch();
5545
5546 w->assertNoEvents();
5547}
5548
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005549TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005550 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5551 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005552
5553 touch();
5554
5555 mTouchWindow->consumeAnyMotionDown();
5556}
5557
5558TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005559 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005560 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005561 w->setFrame(Rect(0, 0, 50, 50));
5562 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005563
5564 touch({PointF{100, 100}});
5565
5566 mTouchWindow->consumeAnyMotionDown();
5567}
5568
5569TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005570 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005571 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005572 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5573
5574 touch();
5575
5576 mTouchWindow->consumeAnyMotionDown();
5577}
5578
5579TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5580 const sp<FakeWindowHandle>& w =
5581 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5582 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005583
5584 touch();
5585
5586 mTouchWindow->consumeAnyMotionDown();
5587}
5588
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005589TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5590 const sp<FakeWindowHandle>& w =
5591 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5592 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5593
5594 touch();
5595
5596 w->assertNoEvents();
5597}
5598
5599/**
5600 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5601 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5602 * window, the occluding window will still receive ACTION_OUTSIDE event.
5603 */
5604TEST_F(InputDispatcherUntrustedTouchesTest,
5605 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5606 const sp<FakeWindowHandle>& w =
5607 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005608 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005609 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5610
5611 touch();
5612
5613 w->consumeMotionOutside();
5614}
5615
5616TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5617 const sp<FakeWindowHandle>& w =
5618 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005619 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005620 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5621
5622 touch();
5623
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005624 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005625}
5626
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005627TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005628 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005629 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5630 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005631 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5632
5633 touch();
5634
5635 mTouchWindow->consumeAnyMotionDown();
5636}
5637
5638TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5639 const sp<FakeWindowHandle>& w =
5640 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5641 MAXIMUM_OBSCURING_OPACITY);
5642 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005643
5644 touch();
5645
5646 mTouchWindow->consumeAnyMotionDown();
5647}
5648
5649TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005650 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005651 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5652 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005653 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5654
5655 touch();
5656
5657 mTouchWindow->assertNoEvents();
5658}
5659
5660TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5661 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5662 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005663 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5664 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005665 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005666 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5667 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005668 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5669
5670 touch();
5671
5672 mTouchWindow->assertNoEvents();
5673}
5674
5675TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5676 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5677 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005678 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5679 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005680 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005681 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5682 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005683 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5684
5685 touch();
5686
5687 mTouchWindow->consumeAnyMotionDown();
5688}
5689
5690TEST_F(InputDispatcherUntrustedTouchesTest,
5691 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5692 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005693 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5694 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005695 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005696 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5697 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005698 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5699
5700 touch();
5701
5702 mTouchWindow->consumeAnyMotionDown();
5703}
5704
5705TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5706 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005707 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5708 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005709 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005710 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5711 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005712 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005713
5714 touch();
5715
5716 mTouchWindow->assertNoEvents();
5717}
5718
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005719TEST_F(InputDispatcherUntrustedTouchesTest,
5720 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5721 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005722 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5723 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005724 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005725 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5726 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005727 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5728
5729 touch();
5730
5731 mTouchWindow->assertNoEvents();
5732}
5733
5734TEST_F(InputDispatcherUntrustedTouchesTest,
5735 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5736 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005737 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5738 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005739 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005740 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5741 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005742 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5743
5744 touch();
5745
5746 mTouchWindow->consumeAnyMotionDown();
5747}
5748
5749TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5750 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005751 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5752 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005753 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5754
5755 touch();
5756
5757 mTouchWindow->consumeAnyMotionDown();
5758}
5759
5760TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5761 const sp<FakeWindowHandle>& w =
5762 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5763 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5764
5765 touch();
5766
5767 mTouchWindow->consumeAnyMotionDown();
5768}
5769
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005770TEST_F(InputDispatcherUntrustedTouchesTest,
5771 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5772 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5773 const sp<FakeWindowHandle>& w =
5774 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5775 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5776
5777 touch();
5778
5779 mTouchWindow->assertNoEvents();
5780}
5781
5782TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5783 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5784 const sp<FakeWindowHandle>& w =
5785 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5786 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5787
5788 touch();
5789
5790 mTouchWindow->consumeAnyMotionDown();
5791}
5792
5793TEST_F(InputDispatcherUntrustedTouchesTest,
5794 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5795 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5796 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005797 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5798 OPACITY_ABOVE_THRESHOLD);
5799 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5800
5801 touch();
5802
5803 mTouchWindow->consumeAnyMotionDown();
5804}
5805
5806TEST_F(InputDispatcherUntrustedTouchesTest,
5807 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5808 const sp<FakeWindowHandle>& w1 =
5809 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5810 OPACITY_BELOW_THRESHOLD);
5811 const sp<FakeWindowHandle>& w2 =
5812 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5813 OPACITY_BELOW_THRESHOLD);
5814 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5815
5816 touch();
5817
5818 mTouchWindow->assertNoEvents();
5819}
5820
5821/**
5822 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5823 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5824 * (which alone would result in allowing touches) does not affect the blocking behavior.
5825 */
5826TEST_F(InputDispatcherUntrustedTouchesTest,
5827 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5828 const sp<FakeWindowHandle>& wB =
5829 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5830 OPACITY_BELOW_THRESHOLD);
5831 const sp<FakeWindowHandle>& wC =
5832 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5833 OPACITY_BELOW_THRESHOLD);
5834 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5835
5836 touch();
5837
5838 mTouchWindow->assertNoEvents();
5839}
5840
5841/**
5842 * This test is testing that a window from a different UID but with same application token doesn't
5843 * block the touch. Apps can share the application token for close UI collaboration for example.
5844 */
5845TEST_F(InputDispatcherUntrustedTouchesTest,
5846 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5847 const sp<FakeWindowHandle>& w =
5848 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5849 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005850 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5851
5852 touch();
5853
5854 mTouchWindow->consumeAnyMotionDown();
5855}
5856
arthurhungb89ccb02020-12-30 16:19:01 +08005857class InputDispatcherDragTests : public InputDispatcherTest {
5858protected:
5859 std::shared_ptr<FakeApplicationHandle> mApp;
5860 sp<FakeWindowHandle> mWindow;
5861 sp<FakeWindowHandle> mSecondWindow;
5862 sp<FakeWindowHandle> mDragWindow;
5863
5864 void SetUp() override {
5865 InputDispatcherTest::SetUp();
5866 mApp = std::make_shared<FakeApplicationHandle>();
5867 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5868 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005869 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005870
5871 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5872 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005873 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005874
5875 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5876 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5877 }
5878
5879 // Start performing drag, we will create a drag window and transfer touch to it.
5880 void performDrag() {
5881 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5882 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5883 {50, 50}))
5884 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5885
5886 // Window should receive motion event.
5887 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5888
5889 // The drag window covers the entire display
5890 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5891 mDispatcher->setInputWindows(
5892 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5893
5894 // Transfer touch focus to the drag window
5895 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5896 true /* isDragDrop */);
5897 mWindow->consumeMotionCancel();
5898 mDragWindow->consumeMotionDown();
5899 }
arthurhung6d4bed92021-03-17 11:59:33 +08005900
5901 // Start performing drag, we will create a drag window and transfer touch to it.
5902 void performStylusDrag() {
5903 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5904 injectMotionEvent(mDispatcher,
5905 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5906 AINPUT_SOURCE_STYLUS)
5907 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5908 .pointer(PointerBuilder(0,
5909 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5910 .x(50)
5911 .y(50))
5912 .build()));
5913 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5914
5915 // The drag window covers the entire display
5916 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5917 mDispatcher->setInputWindows(
5918 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5919
5920 // Transfer touch focus to the drag window
5921 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5922 true /* isDragDrop */);
5923 mWindow->consumeMotionCancel();
5924 mDragWindow->consumeMotionDown();
5925 }
arthurhungb89ccb02020-12-30 16:19:01 +08005926};
5927
5928TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5929 performDrag();
5930
5931 // Move on window.
5932 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5933 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5934 ADISPLAY_ID_DEFAULT, {50, 50}))
5935 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5936 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5937 mWindow->consumeDragEvent(false, 50, 50);
5938 mSecondWindow->assertNoEvents();
5939
5940 // Move to another window.
5941 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5942 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5943 ADISPLAY_ID_DEFAULT, {150, 50}))
5944 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5945 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5946 mWindow->consumeDragEvent(true, 150, 50);
5947 mSecondWindow->consumeDragEvent(false, 50, 50);
5948
5949 // Move back to original window.
5950 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5951 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5952 ADISPLAY_ID_DEFAULT, {50, 50}))
5953 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5954 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5955 mWindow->consumeDragEvent(false, 50, 50);
5956 mSecondWindow->consumeDragEvent(true, -50, 50);
5957
5958 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5959 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5960 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5961 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5962 mWindow->assertNoEvents();
5963 mSecondWindow->assertNoEvents();
5964}
5965
arthurhungf452d0b2021-01-06 00:19:52 +08005966TEST_F(InputDispatcherDragTests, DragAndDrop) {
5967 performDrag();
5968
5969 // Move on window.
5970 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5971 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5972 ADISPLAY_ID_DEFAULT, {50, 50}))
5973 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5974 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5975 mWindow->consumeDragEvent(false, 50, 50);
5976 mSecondWindow->assertNoEvents();
5977
5978 // Move to another window.
5979 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5980 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5981 ADISPLAY_ID_DEFAULT, {150, 50}))
5982 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5983 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5984 mWindow->consumeDragEvent(true, 150, 50);
5985 mSecondWindow->consumeDragEvent(false, 50, 50);
5986
5987 // drop to another window.
5988 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5989 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5990 {150, 50}))
5991 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5992 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5993 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5994 mWindow->assertNoEvents();
5995 mSecondWindow->assertNoEvents();
5996}
5997
arthurhung6d4bed92021-03-17 11:59:33 +08005998TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5999 performStylusDrag();
6000
6001 // Move on window and keep button pressed.
6002 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6003 injectMotionEvent(mDispatcher,
6004 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6005 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6006 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6007 .x(50)
6008 .y(50))
6009 .build()))
6010 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6011 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6012 mWindow->consumeDragEvent(false, 50, 50);
6013 mSecondWindow->assertNoEvents();
6014
6015 // Move to another window and release button, expect to drop item.
6016 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6017 injectMotionEvent(mDispatcher,
6018 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6019 .buttonState(0)
6020 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6021 .x(150)
6022 .y(50))
6023 .build()))
6024 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6025 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6026 mWindow->assertNoEvents();
6027 mSecondWindow->assertNoEvents();
6028 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6029
6030 // nothing to the window.
6031 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6032 injectMotionEvent(mDispatcher,
6033 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6034 .buttonState(0)
6035 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6036 .x(150)
6037 .y(50))
6038 .build()))
6039 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6040 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6041 mWindow->assertNoEvents();
6042 mSecondWindow->assertNoEvents();
6043}
6044
Arthur Hung6d0571e2021-04-09 20:18:16 +08006045TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6046 performDrag();
6047
6048 // Set second window invisible.
6049 mSecondWindow->setVisible(false);
6050 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6051
6052 // Move on window.
6053 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6054 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6055 ADISPLAY_ID_DEFAULT, {50, 50}))
6056 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6057 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6058 mWindow->consumeDragEvent(false, 50, 50);
6059 mSecondWindow->assertNoEvents();
6060
6061 // Move to another window.
6062 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6063 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6064 ADISPLAY_ID_DEFAULT, {150, 50}))
6065 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6066 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6067 mWindow->consumeDragEvent(true, 150, 50);
6068 mSecondWindow->assertNoEvents();
6069
6070 // drop to another window.
6071 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6072 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6073 {150, 50}))
6074 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6075 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6076 mFakePolicy->assertDropTargetEquals(nullptr);
6077 mWindow->assertNoEvents();
6078 mSecondWindow->assertNoEvents();
6079}
6080
Vishnu Nair062a8672021-09-03 16:07:44 -07006081class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6082
6083TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6084 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6085 sp<FakeWindowHandle> window =
6086 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6087 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
6088 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6089 window->setFocusable(true);
6090 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6091 setFocusedWindow(window);
6092 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6093
6094 // With the flag set, window should not get any input
6095 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6096 mDispatcher->notifyKey(&keyArgs);
6097 window->assertNoEvents();
6098
6099 NotifyMotionArgs motionArgs =
6100 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6101 ADISPLAY_ID_DEFAULT);
6102 mDispatcher->notifyMotion(&motionArgs);
6103 window->assertNoEvents();
6104
6105 // With the flag cleared, the window should get input
6106 window->setInputFeatures({});
6107 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6108
6109 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6110 mDispatcher->notifyKey(&keyArgs);
6111 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6112
6113 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6114 ADISPLAY_ID_DEFAULT);
6115 mDispatcher->notifyMotion(&motionArgs);
6116 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6117 window->assertNoEvents();
6118}
6119
6120TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6121 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6122 std::make_shared<FakeApplicationHandle>();
6123 sp<FakeWindowHandle> obscuringWindow =
6124 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6125 ADISPLAY_ID_DEFAULT);
6126 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6127 obscuringWindow->setOwnerInfo(111, 111);
6128 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6129 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6130 sp<FakeWindowHandle> window =
6131 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6132 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6133 window->setOwnerInfo(222, 222);
6134 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6135 window->setFocusable(true);
6136 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6137 setFocusedWindow(window);
6138 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6139
6140 // With the flag set, window should not get any input
6141 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6142 mDispatcher->notifyKey(&keyArgs);
6143 window->assertNoEvents();
6144
6145 NotifyMotionArgs motionArgs =
6146 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6147 ADISPLAY_ID_DEFAULT);
6148 mDispatcher->notifyMotion(&motionArgs);
6149 window->assertNoEvents();
6150
6151 // With the flag cleared, the window should get input
6152 window->setInputFeatures({});
6153 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6154
6155 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6156 mDispatcher->notifyKey(&keyArgs);
6157 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6158
6159 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6160 ADISPLAY_ID_DEFAULT);
6161 mDispatcher->notifyMotion(&motionArgs);
6162 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6163 window->assertNoEvents();
6164}
6165
6166TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6167 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6168 std::make_shared<FakeApplicationHandle>();
6169 sp<FakeWindowHandle> obscuringWindow =
6170 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6171 ADISPLAY_ID_DEFAULT);
6172 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6173 obscuringWindow->setOwnerInfo(111, 111);
6174 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6175 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6176 sp<FakeWindowHandle> window =
6177 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6178 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6179 window->setOwnerInfo(222, 222);
6180 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6181 window->setFocusable(true);
6182 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6183 setFocusedWindow(window);
6184 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6185
6186 // With the flag set, window should not get any input
6187 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6188 mDispatcher->notifyKey(&keyArgs);
6189 window->assertNoEvents();
6190
6191 NotifyMotionArgs motionArgs =
6192 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6193 ADISPLAY_ID_DEFAULT);
6194 mDispatcher->notifyMotion(&motionArgs);
6195 window->assertNoEvents();
6196
6197 // When the window is no longer obscured because it went on top, it should get input
6198 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6199
6200 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6201 mDispatcher->notifyKey(&keyArgs);
6202 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6203
6204 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6205 ADISPLAY_ID_DEFAULT);
6206 mDispatcher->notifyMotion(&motionArgs);
6207 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6208 window->assertNoEvents();
6209}
6210
Antonio Kantekf16f2832021-09-28 04:39:20 +00006211class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6212protected:
6213 std::shared_ptr<FakeApplicationHandle> mApp;
6214 sp<FakeWindowHandle> mWindow;
6215 sp<FakeWindowHandle> mSecondWindow;
6216
6217 void SetUp() override {
6218 InputDispatcherTest::SetUp();
6219
6220 mApp = std::make_shared<FakeApplicationHandle>();
6221 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6222 mWindow->setFocusable(true);
6223 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6224 mSecondWindow->setFocusable(true);
6225
6226 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6227 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6228
6229 setFocusedWindow(mWindow);
6230 mWindow->consumeFocusEvent(true);
6231 }
6232
6233 void changeAndVerifyTouchMode(bool inTouchMode) {
6234 mDispatcher->setInTouchMode(inTouchMode);
6235 mWindow->consumeTouchModeEvent(inTouchMode);
6236 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6237 }
6238};
6239
6240TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
6241 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode);
6242}
6243
6244TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
6245 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode);
6246 mWindow->assertNoEvents();
6247 mSecondWindow->assertNoEvents();
6248}
6249
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006250class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6251public:
6252 sp<FakeWindowHandle> createSpy(const Flags<WindowInfo::Flag> flags) {
6253 std::shared_ptr<FakeApplicationHandle> application =
6254 std::make_shared<FakeApplicationHandle>();
6255 std::string name = "Fake Spy ";
6256 name += std::to_string(mSpyCount++);
6257 sp<FakeWindowHandle> spy =
6258 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
6259 spy->setInputFeatures(WindowInfo::Feature::SPY);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006260 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006261 spy->addFlags(flags);
6262 return spy;
6263 }
6264
6265 sp<FakeWindowHandle> createForeground() {
6266 std::shared_ptr<FakeApplicationHandle> application =
6267 std::make_shared<FakeApplicationHandle>();
6268 sp<FakeWindowHandle> window =
6269 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
6270 window->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006271 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006272 return window;
6273 }
6274
6275private:
6276 int mSpyCount{0};
6277};
6278
6279/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006280 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6281 */
6282TEST_F(InputDispatcherSpyWindowTest, UntrustedSpy_AbortsDispatcher) {
6283 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6284 spy->setTrustedOverlay(false);
6285 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6286 ".* not a trusted overlay");
6287}
6288
6289/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006290 * Input injection into a display with a spy window but no foreground windows should succeed.
6291 */
6292TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
6293 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6294 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6295
6296 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6297 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6298 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6299 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6300}
6301
6302/**
6303 * Verify the order in which different input windows receive events. The touched foreground window
6304 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6305 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6306 * receive events before ones belows it.
6307 *
6308 * Here, we set up a scenario with four windows in the following Z order from the top:
6309 * spy1, spy2, window, spy3.
6310 * We then inject an event and verify that the foreground "window" receives it first, followed by
6311 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6312 * window.
6313 */
6314TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6315 auto window = createForeground();
6316 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6317 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6318 auto spy3 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6319 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6320 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6321 const size_t numChannels = channels.size();
6322
6323 base::unique_fd epollFd(epoll_create1(0 /*flags*/));
6324 if (!epollFd.ok()) {
6325 FAIL() << "Failed to create epoll fd";
6326 }
6327
6328 for (size_t i = 0; i < numChannels; i++) {
6329 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6330 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6331 FAIL() << "Failed to add fd to epoll";
6332 }
6333 }
6334
6335 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6336 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6337 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6338
6339 std::vector<size_t> eventOrder;
6340 std::vector<struct epoll_event> events(numChannels);
6341 for (;;) {
6342 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6343 (100ms).count());
6344 if (nFds < 0) {
6345 FAIL() << "Failed to call epoll_wait";
6346 }
6347 if (nFds == 0) {
6348 break; // epoll_wait timed out
6349 }
6350 for (int i = 0; i < nFds; i++) {
6351 ASSERT_EQ(EPOLLIN, events[i].events);
6352 eventOrder.push_back(events[i].data.u64);
6353 channels[i]->consumeMotionDown();
6354 }
6355 }
6356
6357 // Verify the order in which the events were received.
6358 EXPECT_EQ(3u, eventOrder.size());
6359 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6360 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6361 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6362}
6363
6364/**
6365 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6366 */
6367TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6368 auto window = createForeground();
6369 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCHABLE);
6370 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6371
6372 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6373 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6374 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6375 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6376 spy->assertNoEvents();
6377}
6378
6379/**
6380 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6381 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6382 * to the window.
6383 */
6384TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6385 auto window = createForeground();
6386 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6387 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6388 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6389
6390 // Inject an event outside the spy window's touchable region.
6391 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6392 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6393 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6394 window->consumeMotionDown();
6395 spy->assertNoEvents();
6396 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6397 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6398 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6399 window->consumeMotionUp();
6400 spy->assertNoEvents();
6401
6402 // Inject an event inside the spy window's touchable region.
6403 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6404 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6405 {5, 10}))
6406 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6407 window->consumeMotionDown();
6408 spy->consumeMotionDown();
6409}
6410
6411/**
6412 * A spy window that is a modal window will receive gestures outside of its frame and touchable
6413 * region.
6414 */
6415TEST_F(InputDispatcherSpyWindowTest, ModalWindow) {
6416 auto window = createForeground();
6417 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6418 // This spy window does not have the NOT_TOUCH_MODAL flag set.
6419 spy->setFrame(Rect{0, 0, 20, 20});
6420 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6421
6422 // Inject an event outside the spy window's frame and touchable region.
6423 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6424 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6425 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6426 window->consumeMotionDown();
6427 spy->consumeMotionDown();
6428}
6429
6430/**
6431 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006432 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006433 */
6434TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6435 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006436 window->setOwnerInfo(12, 34);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006437 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006438 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006439 spy->setFrame(Rect{0, 0, 20, 20});
6440 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6441
6442 // Inject an event outside the spy window's frame and touchable region.
6443 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006444 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6445 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006446 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6447 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006448 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006449}
6450
6451/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006452 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6453 * any other windows - including other spy windows - will also be cancelled.
6454 */
6455TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6456 auto window = createForeground();
6457 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6458 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6459 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6460
6461 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6462 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6463 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6464 window->consumeMotionDown();
6465 spy1->consumeMotionDown();
6466 spy2->consumeMotionDown();
6467
6468 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006469 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006470 spy2->assertNoEvents();
6471 spy1->consumeMotionCancel();
6472 window->consumeMotionCancel();
6473
6474 // The rest of the gesture should only be sent to the second spy window.
6475 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6476 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6477 ADISPLAY_ID_DEFAULT))
6478 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6479 spy2->consumeMotionMove();
6480 spy1->assertNoEvents();
6481 window->assertNoEvents();
6482}
6483
6484/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006485 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
6486 * in the middle of the gesture.
6487 */
6488TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
6489 auto window = createForeground();
6490 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6491 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6492
6493 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6494 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6495 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6496 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6497 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6498
6499 window->releaseChannel();
6500
6501 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6502
6503 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6504 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6505 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6506 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6507}
6508
6509/**
6510 * After a spy window pilfers pointers, new pointers that go down should not go to any foreground
6511 * windows.
6512 */
6513TEST_F(InputDispatcherSpyWindowTest, NoSplitAfterPilfer) {
6514 // Create a touch modal spy that spies on the entire display.
6515 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6516
6517 // Create a non touch modal window that supports split touch.
6518 auto window = createForeground();
6519 window->setFrame(Rect(0, 0, 100, 100));
6520 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
6521
6522 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6523
6524 // First finger down, no window touched.
6525 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6526 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6527 {100, 200}))
6528 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6529 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6530 window->assertNoEvents();
6531
6532 // Spy window pilfer the pointers.
6533 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6534
6535 // Second finger down on window, the window should not receive touch down.
6536 const MotionEvent secondFingerDownEvent =
6537 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6538 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6539 AINPUT_SOURCE_TOUCHSCREEN)
6540 .displayId(ADISPLAY_ID_DEFAULT)
6541 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6542 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6543 .x(100)
6544 .y(200))
6545 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6546 .build();
6547 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6548 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6549 InputEventInjectionSync::WAIT_FOR_RESULT))
6550 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6551
6552 window->assertNoEvents();
6553 // Since we no longer allow splitting, the spy will not receive new pointers.
6554 // TODO(b/217376964): Add a way for the pilfering window to receive the rest of the gesture.
6555 spy->consumeMotionMove();
6556}
6557
6558/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006559 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6560 * pointers that are down within its bounds.
6561 */
6562TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6563 auto windowLeft = createForeground();
6564 windowLeft->setFrame({0, 0, 100, 200});
6565 auto windowRight = createForeground();
6566 windowRight->setFrame({100, 0, 200, 200});
6567 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6568 spy->setFrame({0, 0, 200, 200});
6569 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6570
6571 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6572 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6573 {50, 50}))
6574 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6575 windowLeft->consumeMotionDown();
6576 spy->consumeMotionDown();
6577
6578 const MotionEvent secondFingerDownEvent =
6579 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6580 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6581 AINPUT_SOURCE_TOUCHSCREEN)
6582 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6583 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6584 .pointer(
6585 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6586 .build();
6587 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6588 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6589 InputEventInjectionSync::WAIT_FOR_RESULT))
6590 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6591 windowRight->consumeMotionDown();
6592 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6593}
6594
6595/**
6596 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6597 * the spy should receive the second pointer with ACTION_DOWN.
6598 */
6599TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6600 auto window = createForeground();
6601 window->setFrame({0, 0, 200, 200});
6602 auto spyRight = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6603 spyRight->setFrame({100, 0, 200, 200});
6604 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6605
6606 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6607 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6608 {50, 50}))
6609 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6610 window->consumeMotionDown();
6611 spyRight->assertNoEvents();
6612
6613 const MotionEvent secondFingerDownEvent =
6614 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6615 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6616 AINPUT_SOURCE_TOUCHSCREEN)
6617 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6618 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6619 .pointer(
6620 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6621 .build();
6622 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6623 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6624 InputEventInjectionSync::WAIT_FOR_RESULT))
6625 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6626 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6627 spyRight->consumeMotionDown();
6628}
6629
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006630/**
6631 * The spy window should not be able to affect whether or not touches are split. Only the foreground
6632 * windows should be allowed to control split touch.
6633 */
6634TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
6635 // Create a touch modal spy that spies on the entire display.
6636 // This spy window does not set the SPLIT_TOUCH flag. However, we still expect to split touches
6637 // because a foreground window has not disabled splitting.
6638 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6639
6640 // Create a non touch modal window that supports split touch.
6641 auto window = createForeground();
6642 window->setFrame(Rect(0, 0, 100, 100));
6643 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
6644
6645 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6646
6647 // First finger down, no window touched.
6648 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6649 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6650 {100, 200}))
6651 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6652 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6653 window->assertNoEvents();
6654
6655 // Second finger down on window, the window should receive touch down.
6656 const MotionEvent secondFingerDownEvent =
6657 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6658 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6659 AINPUT_SOURCE_TOUCHSCREEN)
6660 .displayId(ADISPLAY_ID_DEFAULT)
6661 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6662 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6663 .x(100)
6664 .y(200))
6665 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6666 .build();
6667 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6668 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6669 InputEventInjectionSync::WAIT_FOR_RESULT))
6670 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6671
6672 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6673 spy->consumeMotionPointerDown(1 /* pointerIndex */);
6674}
6675
6676/**
6677 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
6678 * do not receive key events.
6679 */
6680TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
6681 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6682 spy->setFocusable(false);
6683
6684 auto window = createForeground();
6685 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6686 setFocusedWindow(window);
6687 window->consumeFocusEvent(true);
6688
6689 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6690 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6691 window->consumeKeyDown(ADISPLAY_ID_NONE);
6692
6693 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6694 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6695 window->consumeKeyUp(ADISPLAY_ID_NONE);
6696
6697 spy->assertNoEvents();
6698}
6699
Prabir Pradhand65552b2021-10-07 11:23:50 -07006700class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6701public:
6702 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6703 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6704 std::make_shared<FakeApplicationHandle>();
6705 sp<FakeWindowHandle> overlay =
6706 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6707 ADISPLAY_ID_DEFAULT);
6708 overlay->setFocusable(false);
6709 overlay->setOwnerInfo(111, 111);
6710 overlay->setFlags(WindowInfo::Flag::NOT_TOUCHABLE | WindowInfo::Flag::SPLIT_TOUCH);
6711 overlay->setInputFeatures(WindowInfo::Feature::INTERCEPTS_STYLUS);
6712 overlay->setTrustedOverlay(true);
6713
6714 std::shared_ptr<FakeApplicationHandle> application =
6715 std::make_shared<FakeApplicationHandle>();
6716 sp<FakeWindowHandle> window =
6717 new FakeWindowHandle(application, mDispatcher, "Application window",
6718 ADISPLAY_ID_DEFAULT);
6719 window->setFocusable(true);
6720 window->setOwnerInfo(222, 222);
6721 window->setFlags(WindowInfo::Flag::SPLIT_TOUCH);
6722
6723 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6724 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6725 setFocusedWindow(window);
6726 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6727 return {std::move(overlay), std::move(window)};
6728 }
6729
6730 void sendFingerEvent(int32_t action) {
6731 NotifyMotionArgs motionArgs =
6732 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6733 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6734 mDispatcher->notifyMotion(&motionArgs);
6735 }
6736
6737 void sendStylusEvent(int32_t action) {
6738 NotifyMotionArgs motionArgs =
6739 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6740 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6741 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6742 mDispatcher->notifyMotion(&motionArgs);
6743 }
6744};
6745
6746TEST_F(InputDispatcherStylusInterceptorTest, UntrustedOverlay_AbortsDispatcher) {
6747 auto [overlay, window] = setupStylusOverlayScenario();
6748 overlay->setTrustedOverlay(false);
6749 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6750 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6751 ".* not a trusted overlay");
6752}
6753
6754TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6755 auto [overlay, window] = setupStylusOverlayScenario();
6756 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6757
6758 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6759 overlay->consumeMotionDown();
6760 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6761 overlay->consumeMotionUp();
6762
6763 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6764 window->consumeMotionDown();
6765 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6766 window->consumeMotionUp();
6767
6768 overlay->assertNoEvents();
6769 window->assertNoEvents();
6770}
6771
6772TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6773 auto [overlay, window] = setupStylusOverlayScenario();
6774 overlay->setInputFeatures(overlay->getInfo()->inputFeatures | WindowInfo::Feature::SPY);
6775 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6776
6777 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6778 overlay->consumeMotionDown();
6779 window->consumeMotionDown();
6780 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6781 overlay->consumeMotionUp();
6782 window->consumeMotionUp();
6783
6784 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6785 window->consumeMotionDown();
6786 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6787 window->consumeMotionUp();
6788
6789 overlay->assertNoEvents();
6790 window->assertNoEvents();
6791}
6792
Garfield Tane84e6f92019-08-29 17:28:41 -07006793} // namespace android::inputdispatcher