blob: 612fb84802e4149fab5d201720c5bd9d79abe738 [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>
Prabir Pradhana3ab87a2022-01-27 10:00:21 -080020#include <android-base/silent_death_test.h>
Garfield Tan1c7bc862020-01-28 13:24:04 -080021#include <android-base/stringprintf.h>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070022#include <android-base/thread_annotations.h>
Robert Carr803535b2018-08-02 16:38:15 -070023#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080024#include <gtest/gtest.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100025#include <input/Input.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080026#include <linux/input.h>
Prabir Pradhan07e05b62021-11-19 03:57:24 -080027#include <sys/epoll.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100028
Garfield Tan1c7bc862020-01-28 13:24:04 -080029#include <cinttypes>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070030#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080031#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080032#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
Garfield Tan1c7bc862020-01-28 13:24:04 -080034using android::base::StringPrintf;
chaviw3277faf2021-05-19 16:45:23 -050035using android::gui::FocusRequest;
36using android::gui::TouchOcclusionMode;
37using android::gui::WindowInfo;
38using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080039using android::os::InputEventInjectionResult;
40using android::os::InputEventInjectionSync;
Michael Wright44753b12020-07-08 13:48:11 +010041using namespace android::flag_operators;
Garfield Tan1c7bc862020-01-28 13:24:04 -080042
Garfield Tane84e6f92019-08-29 17:28:41 -070043namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080044
45// An arbitrary time value.
46static const nsecs_t ARBITRARY_TIME = 1234;
47
48// An arbitrary device id.
49static const int32_t DEVICE_ID = 1;
50
Jeff Brownf086ddb2014-02-11 14:28:48 -080051// An arbitrary display id.
Arthur Hungabbb9d82021-09-01 14:52:30 +000052static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
53static constexpr int32_t SECOND_DISPLAY_ID = 1;
Jeff Brownf086ddb2014-02-11 14:28:48 -080054
Michael Wrightd02c5b62014-02-10 15:10:22 -080055// An arbitrary injector pid / uid pair that has permission to inject events.
56static const int32_t INJECTOR_PID = 999;
57static const int32_t INJECTOR_UID = 1001;
58
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000059// An arbitrary pid of the gesture monitor window
60static constexpr int32_t MONITOR_PID = 2001;
61
chaviwd1c23182019-12-20 18:44:56 -080062struct PointF {
63 float x;
64 float y;
65};
Michael Wrightd02c5b62014-02-10 15:10:22 -080066
Gang Wang342c9272020-01-13 13:15:04 -050067/**
68 * Return a DOWN key event with KEYCODE_A.
69 */
70static KeyEvent getTestKeyEvent() {
71 KeyEvent event;
72
Garfield Tanfbe732e2020-01-24 11:26:14 -080073 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
74 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
75 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050076 return event;
77}
78
Siarhei Vishniakouca205502021-07-16 21:31:58 +000079static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
80 ASSERT_EQ(expectedAction, receivedAction)
81 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
82 << MotionEvent::actionToString(receivedAction);
83}
84
Michael Wrightd02c5b62014-02-10 15:10:22 -080085// --- FakeInputDispatcherPolicy ---
86
87class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
88 InputDispatcherConfiguration mConfig;
89
90protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100091 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
93public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100094 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +080095
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080096 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -070097 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
98 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
99 EXPECT_EQ(event.getDisplayId(), args.displayId);
100
101 const auto& keyEvent = static_cast<const KeyEvent&>(event);
102 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
103 EXPECT_EQ(keyEvent.getAction(), args.action);
104 });
Jackal Guof9696682018-10-05 12:23:23 +0800105 }
106
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700107 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
108 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
109 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
110 EXPECT_EQ(event.getDisplayId(), args.displayId);
111
112 const auto& motionEvent = static_cast<const MotionEvent&>(event);
113 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
114 EXPECT_EQ(motionEvent.getAction(), args.action);
115 EXPECT_EQ(motionEvent.getX(0), point.x);
116 EXPECT_EQ(motionEvent.getY(0), point.y);
117 EXPECT_EQ(motionEvent.getRawX(0), point.x);
118 EXPECT_EQ(motionEvent.getRawY(0), point.y);
119 });
Jackal Guof9696682018-10-05 12:23:23 +0800120 }
121
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700122 void assertFilterInputEventWasNotCalled() {
123 std::scoped_lock lock(mLock);
124 ASSERT_EQ(nullptr, mFilteredEvent);
125 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800127 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700128 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800129 ASSERT_TRUE(mConfigurationChangedTime)
130 << "Timed out waiting for configuration changed call";
131 ASSERT_EQ(*mConfigurationChangedTime, when);
132 mConfigurationChangedTime = std::nullopt;
133 }
134
135 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700136 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800137 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800138 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800139 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
140 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
141 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
142 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
143 mLastNotifySwitch = std::nullopt;
144 }
145
chaviwfd6d3512019-03-25 13:23:49 -0700146 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700147 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800148 ASSERT_EQ(touchedToken, mOnPointerDownToken);
149 mOnPointerDownToken.clear();
150 }
151
152 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700153 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800154 ASSERT_TRUE(mOnPointerDownToken == nullptr)
155 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700156 }
157
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700158 // This function must be called soon after the expected ANR timer starts,
159 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500160 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700161 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500162 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
163 std::shared_ptr<InputApplicationHandle> application;
164 { // acquire lock
165 std::unique_lock lock(mLock);
166 android::base::ScopedLockAssertion assumeLocked(mLock);
167 ASSERT_NO_FATAL_FAILURE(
168 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
169 } // release lock
170 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700171 }
172
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000173 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
174 const sp<IBinder>& expectedConnectionToken) {
175 sp<IBinder> connectionToken = getUnresponsiveWindowToken(timeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500176 ASSERT_EQ(expectedConnectionToken, connectionToken);
177 }
178
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000179 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
180 sp<IBinder> connectionToken = getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500181 ASSERT_EQ(expectedConnectionToken, connectionToken);
182 }
183
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000184 void assertNotifyMonitorUnresponsiveWasCalled(std::chrono::nanoseconds timeout) {
185 int32_t pid = getUnresponsiveMonitorPid(timeout);
186 ASSERT_EQ(MONITOR_PID, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500187 }
188
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000189 void assertNotifyMonitorResponsiveWasCalled() {
190 int32_t pid = getResponsiveMonitorPid();
191 ASSERT_EQ(MONITOR_PID, pid);
192 }
193
194 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500195 std::unique_lock lock(mLock);
196 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000197 return getAnrTokenLockedInterruptible(timeout, mAnrWindowTokens, lock);
198 }
199
200 sp<IBinder> getResponsiveWindowToken() {
201 std::unique_lock lock(mLock);
202 android::base::ScopedLockAssertion assumeLocked(mLock);
203 return getAnrTokenLockedInterruptible(0s, mResponsiveWindowTokens, lock);
204 }
205
206 int32_t getUnresponsiveMonitorPid(std::chrono::nanoseconds timeout) {
207 std::unique_lock lock(mLock);
208 android::base::ScopedLockAssertion assumeLocked(mLock);
209 return getAnrTokenLockedInterruptible(timeout, mAnrMonitorPids, lock);
210 }
211
212 int32_t getResponsiveMonitorPid() {
213 std::unique_lock lock(mLock);
214 android::base::ScopedLockAssertion assumeLocked(mLock);
215 return getAnrTokenLockedInterruptible(0s, mResponsiveMonitorPids, lock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500216 }
217
218 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
219 // for a specific container to become non-empty. When the container is non-empty, return the
220 // first entry from the container and erase it.
221 template <class T>
222 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
223 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700224 // If there is an ANR, Dispatcher won't be idle because there are still events
225 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
226 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500227 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
228 // to provide it some time to act. 100ms seems reasonable.
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800229 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
230 const std::chrono::time_point start = std::chrono::steady_clock::now();
231 std::optional<T> token =
232 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
233 if (!token.has_value()) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500234 ADD_FAILURE() << "Did not receive the ANR callback";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000235 return {};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700236 }
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800237
238 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700239 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
240 // the dispatcher started counting before this function was called
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700241 if (std::chrono::abs(timeout - waited) > 100ms) {
242 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
243 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
244 << "ms, but waited "
245 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
246 << "ms instead";
247 }
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800248 return *token;
249 }
250
251 template <class T>
252 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
253 std::queue<T>& storage,
254 std::unique_lock<std::mutex>& lock,
255 std::condition_variable& condition)
256 REQUIRES(mLock) {
257 condition.wait_for(lock, timeout,
258 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
259 if (storage.empty()) {
260 ADD_FAILURE() << "Did not receive the expected callback";
261 return std::nullopt;
262 }
263 T item = storage.front();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500264 storage.pop();
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800265 return std::make_optional(item);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700266 }
267
268 void assertNotifyAnrWasNotCalled() {
269 std::scoped_lock lock(mLock);
270 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000271 ASSERT_TRUE(mAnrWindowTokens.empty());
272 ASSERT_TRUE(mAnrMonitorPids.empty());
273 ASSERT_TRUE(mResponsiveWindowTokens.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500274 << "ANR was not called, but please also consume the 'connection is responsive' "
275 "signal";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000276 ASSERT_TRUE(mResponsiveMonitorPids.empty())
277 << "Monitor ANR was not called, but please also consume the 'monitor is responsive'"
278 " signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700279 }
280
Garfield Tan1c7bc862020-01-28 13:24:04 -0800281 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
282 mConfig.keyRepeatTimeout = timeout;
283 mConfig.keyRepeatDelay = delay;
284 }
285
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000286 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800287 std::unique_lock lock(mLock);
288 base::ScopedLockAssertion assumeLocked(mLock);
289
290 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
291 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000292 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800293 enabled;
294 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000295 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
296 << ") to be called.";
297 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800298 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000299 auto request = *mPointerCaptureRequest;
300 mPointerCaptureRequest.reset();
301 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800302 }
303
304 void assertSetPointerCaptureNotCalled() {
305 std::unique_lock lock(mLock);
306 base::ScopedLockAssertion assumeLocked(mLock);
307
308 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000309 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800310 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000311 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800312 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000313 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800314 }
315
arthurhungf452d0b2021-01-06 00:19:52 +0800316 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
317 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800318 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800319 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800320 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800321 }
322
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800323 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
324 std::unique_lock lock(mLock);
325 base::ScopedLockAssertion assumeLocked(mLock);
326 std::optional<sp<IBinder>> receivedToken =
327 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
328 mNotifyInputChannelBroken);
329 ASSERT_TRUE(receivedToken.has_value());
330 ASSERT_EQ(token, *receivedToken);
331 }
332
Michael Wrightd02c5b62014-02-10 15:10:22 -0800333private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700334 std::mutex mLock;
335 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
336 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
337 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
338 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800339
Prabir Pradhan99987712020-11-10 18:43:05 -0800340 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000341
342 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800343
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700344 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700345 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000346 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
347 std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
348 std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
349 std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700350 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800351 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
352 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700353
arthurhungf452d0b2021-01-06 00:19:52 +0800354 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800355 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800356
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600357 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700358 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800359 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800360 }
361
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000362 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700363 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000364 mAnrWindowTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700365 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500366 }
367
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000368 void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500369 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000370 mAnrMonitorPids.push(pid);
371 mNotifyAnr.notify_all();
372 }
373
374 void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
375 std::scoped_lock lock(mLock);
376 mResponsiveWindowTokens.push(connectionToken);
377 mNotifyAnr.notify_all();
378 }
379
380 void notifyMonitorResponsive(int32_t pid) override {
381 std::scoped_lock lock(mLock);
382 mResponsiveMonitorPids.push(pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500383 mNotifyAnr.notify_all();
384 }
385
386 void notifyNoFocusedWindowAnr(
387 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
388 std::scoped_lock lock(mLock);
389 mAnrApplications.push(applicationHandle);
390 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800391 }
392
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800393 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
394 std::scoped_lock lock(mLock);
395 mBrokenInputChannels.push(connectionToken);
396 mNotifyInputChannelBroken.notify_all();
397 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800398
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600399 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700400
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600401 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700402 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
403 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
404 const std::vector<float>& values) override {}
405
406 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
407 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000408
Chris Yefb552902021-02-03 17:18:37 -0800409 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
410
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600411 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800412 *outConfig = mConfig;
413 }
414
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600415 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700416 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800417 switch (inputEvent->getType()) {
418 case AINPUT_EVENT_TYPE_KEY: {
419 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800420 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800421 break;
422 }
423
424 case AINPUT_EVENT_TYPE_MOTION: {
425 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800426 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800427 break;
428 }
429 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800430 return true;
431 }
432
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600433 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800434
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600435 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800436
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600437 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800438 return 0;
439 }
440
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600441 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800442 return false;
443 }
444
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600445 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
446 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700447 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800448 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
449 * essentially a passthrough for notifySwitch.
450 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800451 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800452 }
453
Sean Stoutb4e0a592021-02-23 07:34:53 -0800454 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800456 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
457 return pid == INJECTOR_PID && uid == INJECTOR_UID;
458 }
Jackal Guof9696682018-10-05 12:23:23 +0800459
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600460 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700461 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700462 mOnPointerDownToken = newToken;
463 }
464
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000465 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800466 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000467 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800468 mPointerCaptureChangedCondition.notify_all();
469 }
470
arthurhungf452d0b2021-01-06 00:19:52 +0800471 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
472 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800473 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800474 mDropTargetWindowToken = token;
475 }
476
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700477 void assertFilterInputEventWasCalledInternal(
478 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700479 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800480 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700481 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800482 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800484};
485
Michael Wrightd02c5b62014-02-10 15:10:22 -0800486// --- InputDispatcherTest ---
487
488class InputDispatcherTest : public testing::Test {
489protected:
490 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700491 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000493 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800494 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700495 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800496 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000497 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700498 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800499 }
500
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000501 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700502 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800503 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700504 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700506
507 /**
508 * Used for debugging when writing the test
509 */
510 void dumpDispatcherState() {
511 std::string dump;
512 mDispatcher->dump(dump);
513 std::stringstream ss(dump);
514 std::string to;
515
516 while (std::getline(ss, to, '\n')) {
517 ALOGE("%s", to.c_str());
518 }
519 }
Vishnu Nair958da932020-08-21 17:12:37 -0700520
chaviw3277faf2021-05-19 16:45:23 -0500521 void setFocusedWindow(const sp<WindowInfoHandle>& window,
522 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700523 FocusRequest request;
524 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000525 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700526 if (focusedWindow) {
527 request.focusedToken = focusedWindow->getToken();
528 }
529 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
530 request.displayId = window->getInfo()->displayId;
531 mDispatcher->setFocusedWindow(request);
532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533};
534
Michael Wrightd02c5b62014-02-10 15:10:22 -0800535TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
536 KeyEvent event;
537
538 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800539 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
540 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600541 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
542 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800543 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700544 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800545 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800546 << "Should reject key events with undefined action.";
547
548 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800549 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
550 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600551 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800552 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700553 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800554 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800555 << "Should reject key events with ACTION_MULTIPLE.";
556}
557
558TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
559 MotionEvent event;
560 PointerProperties pointerProperties[MAX_POINTERS + 1];
561 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800562 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563 pointerProperties[i].clear();
564 pointerProperties[i].id = i;
565 pointerCoords[i].clear();
566 }
567
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800568 // Some constants commonly used below
569 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
570 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
571 constexpr int32_t metaState = AMETA_NONE;
572 constexpr MotionClassification classification = MotionClassification::NONE;
573
chaviw9eaa22c2020-07-01 16:21:27 -0700574 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800575 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800576 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700577 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
578 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700579 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
580 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700581 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800582 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700583 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800584 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800585 << "Should reject motion events with undefined action.";
586
587 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800588 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700589 AMOTION_EVENT_ACTION_POINTER_DOWN |
590 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700591 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
592 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700593 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500594 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800595 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700596 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800597 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598 << "Should reject motion events with pointer down index too large.";
599
Garfield Tanfbe732e2020-01-24 11:26:14 -0800600 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700601 AMOTION_EVENT_ACTION_POINTER_DOWN |
602 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700603 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
604 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700605 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500606 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800607 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700608 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800609 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800610 << "Should reject motion events with pointer down index too small.";
611
612 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800613 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700614 AMOTION_EVENT_ACTION_POINTER_UP |
615 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700616 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
617 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700618 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500619 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800620 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700621 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800622 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800623 << "Should reject motion events with pointer up index too large.";
624
Garfield Tanfbe732e2020-01-24 11:26:14 -0800625 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700626 AMOTION_EVENT_ACTION_POINTER_UP |
627 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700628 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
629 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700630 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500631 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800632 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700633 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800634 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800635 << "Should reject motion events with pointer up index too small.";
636
637 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800638 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
639 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700640 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700641 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
642 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700643 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800644 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700645 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800646 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800647 << "Should reject motion events with 0 pointers.";
648
Garfield Tanfbe732e2020-01-24 11:26:14 -0800649 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
650 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700651 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700652 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
653 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700654 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800655 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700656 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800657 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800658 << "Should reject motion events with more than MAX_POINTERS pointers.";
659
660 // Rejects motion events with invalid pointer ids.
661 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800662 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
663 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700664 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700665 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
666 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700667 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800668 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700669 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800670 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800671 << "Should reject motion events with pointer ids less than 0.";
672
673 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800674 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
675 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700676 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700677 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
678 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700679 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800680 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700681 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800682 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800683 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
684
685 // Rejects motion events with duplicate pointer ids.
686 pointerProperties[0].id = 1;
687 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800688 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
689 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700690 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700691 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
692 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700693 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800694 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700695 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800696 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697 << "Should reject motion events with duplicate pointer ids.";
698}
699
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800700/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
701
702TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
703 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800704 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800705 mDispatcher->notifyConfigurationChanged(&args);
706 ASSERT_TRUE(mDispatcher->waitForIdle());
707
708 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
709}
710
711TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800712 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
713 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800714 mDispatcher->notifySwitch(&args);
715
716 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
717 args.policyFlags |= POLICY_FLAG_TRUSTED;
718 mFakePolicy->assertNotifySwitchWasCalled(args);
719}
720
Arthur Hungb92218b2018-08-14 12:00:21 +0800721// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700722static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700723// Default input dispatching timeout if there is no focused application or paused window
724// from which to determine an appropriate dispatching timeout.
725static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
726 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
727 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800728
729class FakeApplicationHandle : public InputApplicationHandle {
730public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700731 FakeApplicationHandle() {
732 mInfo.name = "Fake Application";
733 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500734 mInfo.dispatchingTimeoutMillis =
735 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700736 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800737 virtual ~FakeApplicationHandle() {}
738
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000739 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700740
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500741 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
742 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700743 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800744};
745
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800746class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800747public:
Garfield Tan15601662020-09-22 15:32:38 -0700748 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800749 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700750 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800751 }
752
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800753 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700754 InputEvent* event;
755 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
756 if (!consumeSeq) {
757 return nullptr;
758 }
759 finishEvent(*consumeSeq);
760 return event;
761 }
762
763 /**
764 * Receive an event without acknowledging it.
765 * Return the sequence number that could later be used to send finished signal.
766 */
767 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800768 uint32_t consumeSeq;
769 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800770
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800771 std::chrono::time_point start = std::chrono::steady_clock::now();
772 status_t status = WOULD_BLOCK;
773 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800774 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800775 &event);
776 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
777 if (elapsed > 100ms) {
778 break;
779 }
780 }
781
782 if (status == WOULD_BLOCK) {
783 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700784 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800785 }
786
787 if (status != OK) {
788 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700789 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800790 }
791 if (event == nullptr) {
792 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700793 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800794 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700795 if (outEvent != nullptr) {
796 *outEvent = event;
797 }
798 return consumeSeq;
799 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800800
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700801 /**
802 * To be used together with "receiveEvent" to complete the consumption of an event.
803 */
804 void finishEvent(uint32_t consumeSeq) {
805 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
806 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800807 }
808
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000809 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
810 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
811 ASSERT_EQ(OK, status);
812 }
813
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000814 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
815 std::optional<int32_t> expectedDisplayId,
816 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800817 InputEvent* event = consume();
818
819 ASSERT_NE(nullptr, event) << mName.c_str()
820 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800821 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700822 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800823 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800824
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000825 if (expectedDisplayId.has_value()) {
826 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
827 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800828
Tiger Huang8664f8c2018-10-11 19:14:35 +0800829 switch (expectedEventType) {
830 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800831 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
832 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000833 if (expectedFlags.has_value()) {
834 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
835 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800836 break;
837 }
838 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800839 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000840 assertMotionAction(expectedAction, motionEvent.getAction());
841
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000842 if (expectedFlags.has_value()) {
843 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
844 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800845 break;
846 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100847 case AINPUT_EVENT_TYPE_FOCUS: {
848 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
849 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800850 case AINPUT_EVENT_TYPE_CAPTURE: {
851 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
852 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000853 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
854 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
855 }
arthurhungb89ccb02020-12-30 16:19:01 +0800856 case AINPUT_EVENT_TYPE_DRAG: {
857 FAIL() << "Use 'consumeDragEvent' for DRAG events";
858 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800859 default: {
860 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
861 }
862 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800863 }
864
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100865 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
866 InputEvent* event = consume();
867 ASSERT_NE(nullptr, event) << mName.c_str()
868 << ": consumer should have returned non-NULL event.";
869 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
870 << "Got " << inputEventTypeToString(event->getType())
871 << " event instead of FOCUS event";
872
873 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
874 << mName.c_str() << ": event displayId should always be NONE.";
875
876 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
877 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100878 }
879
Prabir Pradhan99987712020-11-10 18:43:05 -0800880 void consumeCaptureEvent(bool hasCapture) {
881 const InputEvent* event = consume();
882 ASSERT_NE(nullptr, event) << mName.c_str()
883 << ": consumer should have returned non-NULL event.";
884 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
885 << "Got " << inputEventTypeToString(event->getType())
886 << " event instead of CAPTURE event";
887
888 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
889 << mName.c_str() << ": event displayId should always be NONE.";
890
891 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
892 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
893 }
894
arthurhungb89ccb02020-12-30 16:19:01 +0800895 void consumeDragEvent(bool isExiting, float x, float y) {
896 const InputEvent* event = consume();
897 ASSERT_NE(nullptr, event) << mName.c_str()
898 << ": consumer should have returned non-NULL event.";
899 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
900 << "Got " << inputEventTypeToString(event->getType())
901 << " event instead of DRAG event";
902
903 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
904 << mName.c_str() << ": event displayId should always be NONE.";
905
906 const auto& dragEvent = static_cast<const DragEvent&>(*event);
907 EXPECT_EQ(isExiting, dragEvent.isExiting());
908 EXPECT_EQ(x, dragEvent.getX());
909 EXPECT_EQ(y, dragEvent.getY());
910 }
911
Antonio Kantekf16f2832021-09-28 04:39:20 +0000912 void consumeTouchModeEvent(bool inTouchMode) {
913 const InputEvent* event = consume();
914 ASSERT_NE(nullptr, event) << mName.c_str()
915 << ": consumer should have returned non-NULL event.";
916 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
917 << "Got " << inputEventTypeToString(event->getType())
918 << " event instead of TOUCH_MODE event";
919
920 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
921 << mName.c_str() << ": event displayId should always be NONE.";
922 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
923 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
924 }
925
chaviwd1c23182019-12-20 18:44:56 -0800926 void assertNoEvents() {
927 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700928 if (event == nullptr) {
929 return;
930 }
931 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
932 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
933 ADD_FAILURE() << "Received key event "
934 << KeyEvent::actionToString(keyEvent.getAction());
935 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
936 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
937 ADD_FAILURE() << "Received motion event "
938 << MotionEvent::actionToString(motionEvent.getAction());
939 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
940 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
941 ADD_FAILURE() << "Received focus event, hasFocus = "
942 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800943 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
944 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
945 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
946 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000947 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
948 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
949 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
950 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700951 }
952 FAIL() << mName.c_str()
953 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800954 }
955
956 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
957
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800958 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
959
chaviwd1c23182019-12-20 18:44:56 -0800960protected:
961 std::unique_ptr<InputConsumer> mConsumer;
962 PreallocatedInputEventFactory mEventFactory;
963
964 std::string mName;
965};
966
chaviw3277faf2021-05-19 16:45:23 -0500967class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800968public:
969 static const int32_t WIDTH = 600;
970 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800971
Chris Yea209fde2020-07-22 13:54:51 -0700972 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700973 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500974 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800975 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500976 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700977 base::Result<std::unique_ptr<InputChannel>> channel =
978 dispatcher->createInputChannel(name);
979 token = (*channel)->getConnectionToken();
980 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800981 }
982
983 inputApplicationHandle->updateInfo();
984 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
985
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500986 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700987 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800988 mInfo.name = name;
chaviw3277faf2021-05-19 16:45:23 -0500989 mInfo.type = WindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500990 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000991 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800992 mInfo.frameLeft = 0;
993 mInfo.frameTop = 0;
994 mInfo.frameRight = WIDTH;
995 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700996 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800997 mInfo.globalScaleFactor = 1.0;
998 mInfo.touchableRegion.clear();
999 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
1000 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -07001001 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -08001002 mInfo.hasWallpaper = false;
1003 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -08001004 mInfo.ownerPid = INJECTOR_PID;
1005 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -08001006 mInfo.displayId = displayId;
Prabir Pradhand65552b2021-10-07 11:23:50 -07001007 mInfo.trustedOverlay = false;
chaviwd1c23182019-12-20 18:44:56 -08001008 }
1009
Arthur Hungabbb9d82021-09-01 14:52:30 +00001010 sp<FakeWindowHandle> clone(
1011 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001012 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001013 sp<FakeWindowHandle> handle =
1014 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1015 displayId, mInfo.token);
1016 return handle;
1017 }
1018
Vishnu Nair47074b82020-08-14 11:54:47 -07001019 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -08001020
Vishnu Nair958da932020-08-21 17:12:37 -07001021 void setVisible(bool visible) { mInfo.visible = visible; }
1022
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001023 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001024 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001025 }
1026
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001027 void setPaused(bool paused) { mInfo.paused = paused; }
1028
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001029 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1030
chaviw3277faf2021-05-19 16:45:23 -05001031 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001032
Bernardo Rufino7393d172021-02-26 13:56:11 +00001033 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1034
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001035 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001036 mInfo.frameLeft = frame.left;
1037 mInfo.frameTop = frame.top;
1038 mInfo.frameRight = frame.right;
1039 mInfo.frameBottom = frame.bottom;
1040 mInfo.touchableRegion.clear();
1041 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001042
1043 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1044 ui::Transform translate;
1045 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1046 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001047 }
1048
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001049 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1050
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001051 void setType(WindowInfo::Type type) { mInfo.type = type; }
1052
1053 void setHasWallpaper(bool hasWallpaper) { mInfo.hasWallpaper = hasWallpaper; }
1054
chaviw3277faf2021-05-19 16:45:23 -05001055 void addFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags |= flags; }
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00001056
chaviw3277faf2021-05-19 16:45:23 -05001057 void setFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -08001058
Prabir Pradhand65552b2021-10-07 11:23:50 -07001059 void setInputFeatures(Flags<WindowInfo::Feature> features) { mInfo.inputFeatures = features; }
1060
1061 void setTrustedOverlay(bool trustedOverlay) { mInfo.trustedOverlay = trustedOverlay; }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001062
chaviw9eaa22c2020-07-01 16:21:27 -07001063 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1064 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1065 }
1066
1067 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001068
yunho.shinf4a80b82020-11-16 21:13:57 +09001069 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1070
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001071 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1072 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1073 expectedFlags);
1074 }
1075
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001076 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1077 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1078 }
1079
Svet Ganov5d3bc372020-01-26 23:11:07 -08001080 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001081 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001082 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1083 expectedFlags);
1084 }
1085
1086 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001087 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001088 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1089 expectedFlags);
1090 }
1091
1092 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001093 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001094 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1095 }
1096
1097 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1098 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001099 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1100 expectedFlags);
1101 }
1102
Svet Ganov5d3bc372020-01-26 23:11:07 -08001103 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001104 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1105 int32_t expectedFlags = 0) {
1106 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1107 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001108 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1109 }
1110
1111 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001112 int32_t expectedFlags = 0) {
1113 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1114 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001115 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1116 }
1117
1118 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001119 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001120 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1121 expectedFlags);
1122 }
1123
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001124 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1125 int32_t expectedFlags = 0) {
1126 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1127 expectedFlags);
1128 }
1129
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001130 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1131 int32_t expectedFlags = 0) {
1132 InputEvent* event = consume();
1133 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1134 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1135 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1136 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1137 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1138 }
1139
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001140 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1141 ASSERT_NE(mInputReceiver, nullptr)
1142 << "Cannot consume events from a window with no receiver";
1143 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1144 }
1145
Prabir Pradhan99987712020-11-10 18:43:05 -08001146 void consumeCaptureEvent(bool hasCapture) {
1147 ASSERT_NE(mInputReceiver, nullptr)
1148 << "Cannot consume events from a window with no receiver";
1149 mInputReceiver->consumeCaptureEvent(hasCapture);
1150 }
1151
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001152 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1153 std::optional<int32_t> expectedDisplayId,
1154 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001155 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1156 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1157 expectedFlags);
1158 }
1159
arthurhungb89ccb02020-12-30 16:19:01 +08001160 void consumeDragEvent(bool isExiting, float x, float y) {
1161 mInputReceiver->consumeDragEvent(isExiting, x, y);
1162 }
1163
Antonio Kantekf16f2832021-09-28 04:39:20 +00001164 void consumeTouchModeEvent(bool inTouchMode) {
1165 ASSERT_NE(mInputReceiver, nullptr)
1166 << "Cannot consume events from a window with no receiver";
1167 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1168 }
1169
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001170 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001171 if (mInputReceiver == nullptr) {
1172 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1173 return std::nullopt;
1174 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001175 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001176 }
1177
1178 void finishEvent(uint32_t sequenceNum) {
1179 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1180 mInputReceiver->finishEvent(sequenceNum);
1181 }
1182
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001183 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1184 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1185 mInputReceiver->sendTimeline(inputEventId, timeline);
1186 }
1187
chaviwaf87b3e2019-10-01 16:59:28 -07001188 InputEvent* consume() {
1189 if (mInputReceiver == nullptr) {
1190 return nullptr;
1191 }
1192 return mInputReceiver->consume();
1193 }
1194
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001195 MotionEvent* consumeMotion() {
1196 InputEvent* event = consume();
1197 if (event == nullptr) {
1198 ADD_FAILURE() << "Consume failed : no event";
1199 return nullptr;
1200 }
1201 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1202 ADD_FAILURE() << "Instead of motion event, got "
1203 << inputEventTypeToString(event->getType());
1204 return nullptr;
1205 }
1206 return static_cast<MotionEvent*>(event);
1207 }
1208
Arthur Hungb92218b2018-08-14 12:00:21 +08001209 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001210 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001211 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001212 return; // Can't receive events if the window does not have input channel
1213 }
1214 ASSERT_NE(nullptr, mInputReceiver)
1215 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001216 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001217 }
1218
chaviwaf87b3e2019-10-01 16:59:28 -07001219 sp<IBinder> getToken() { return mInfo.token; }
1220
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001221 const std::string& getName() { return mName; }
1222
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001223 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1224 mInfo.ownerPid = ownerPid;
1225 mInfo.ownerUid = ownerUid;
1226 }
1227
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001228 void destroyReceiver() { mInputReceiver = nullptr; }
1229
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001230 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1231
chaviwd1c23182019-12-20 18:44:56 -08001232private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001233 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001234 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001235 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001236};
1237
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001238std::atomic<int32_t> FakeWindowHandle::sId{1};
1239
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001240static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001241 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001242 int32_t displayId = ADISPLAY_ID_NONE,
1243 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001244 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1245 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001246 KeyEvent event;
1247 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1248
1249 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001250 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001251 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1252 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001253
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001254 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1255 if (!allowKeyRepeat) {
1256 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1257 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001258 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001259 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001260 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001261}
1262
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001263static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001264 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001265 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1266}
1267
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001268// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1269// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1270// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001271static InputEventInjectionResult injectKeyDownNoRepeat(
1272 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001273 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1274 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1275 /* allowKeyRepeat */ false);
1276}
1277
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001278static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001279 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001280 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1281}
1282
Garfield Tandf26e862020-07-01 20:18:19 -07001283class PointerBuilder {
1284public:
1285 PointerBuilder(int32_t id, int32_t toolType) {
1286 mProperties.clear();
1287 mProperties.id = id;
1288 mProperties.toolType = toolType;
1289 mCoords.clear();
1290 }
1291
1292 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1293
1294 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1295
1296 PointerBuilder& axis(int32_t axis, float value) {
1297 mCoords.setAxisValue(axis, value);
1298 return *this;
1299 }
1300
1301 PointerProperties buildProperties() const { return mProperties; }
1302
1303 PointerCoords buildCoords() const { return mCoords; }
1304
1305private:
1306 PointerProperties mProperties;
1307 PointerCoords mCoords;
1308};
1309
1310class MotionEventBuilder {
1311public:
1312 MotionEventBuilder(int32_t action, int32_t source) {
1313 mAction = action;
1314 mSource = source;
1315 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1316 }
1317
1318 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1319 mEventTime = eventTime;
1320 return *this;
1321 }
1322
1323 MotionEventBuilder& displayId(int32_t displayId) {
1324 mDisplayId = displayId;
1325 return *this;
1326 }
1327
1328 MotionEventBuilder& actionButton(int32_t actionButton) {
1329 mActionButton = actionButton;
1330 return *this;
1331 }
1332
arthurhung6d4bed92021-03-17 11:59:33 +08001333 MotionEventBuilder& buttonState(int32_t buttonState) {
1334 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001335 return *this;
1336 }
1337
1338 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1339 mRawXCursorPosition = rawXCursorPosition;
1340 return *this;
1341 }
1342
1343 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1344 mRawYCursorPosition = rawYCursorPosition;
1345 return *this;
1346 }
1347
1348 MotionEventBuilder& pointer(PointerBuilder pointer) {
1349 mPointers.push_back(pointer);
1350 return *this;
1351 }
1352
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001353 MotionEventBuilder& addFlag(uint32_t flags) {
1354 mFlags |= flags;
1355 return *this;
1356 }
1357
Garfield Tandf26e862020-07-01 20:18:19 -07001358 MotionEvent build() {
1359 std::vector<PointerProperties> pointerProperties;
1360 std::vector<PointerCoords> pointerCoords;
1361 for (const PointerBuilder& pointer : mPointers) {
1362 pointerProperties.push_back(pointer.buildProperties());
1363 pointerCoords.push_back(pointer.buildCoords());
1364 }
1365
1366 // Set mouse cursor position for the most common cases to avoid boilerplate.
1367 if (mSource == AINPUT_SOURCE_MOUSE &&
1368 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1369 mPointers.size() == 1) {
1370 mRawXCursorPosition = pointerCoords[0].getX();
1371 mRawYCursorPosition = pointerCoords[0].getY();
1372 }
1373
1374 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001375 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001376 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001377 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001378 mButtonState, MotionClassification::NONE, identityTransform,
1379 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001380 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1381 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001382
1383 return event;
1384 }
1385
1386private:
1387 int32_t mAction;
1388 int32_t mSource;
1389 nsecs_t mEventTime;
1390 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1391 int32_t mActionButton{0};
1392 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001393 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001394 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1395 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1396
1397 std::vector<PointerBuilder> mPointers;
1398};
1399
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001400static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001401 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001402 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001403 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001404 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1405 injectionTimeout,
1406 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1407}
1408
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001409static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001410 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001411 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001412 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001413 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1414 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001415 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001416 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001417 MotionEvent event = MotionEventBuilder(action, source)
1418 .displayId(displayId)
1419 .eventTime(eventTime)
1420 .rawXCursorPosition(cursorPosition.x)
1421 .rawYCursorPosition(cursorPosition.y)
1422 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1423 .x(position.x)
1424 .y(position.y))
1425 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001426
1427 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001428 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001429}
1430
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001431static InputEventInjectionResult injectMotionDown(
1432 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1433 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001434 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001435}
1436
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001437static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001438 int32_t source, int32_t displayId,
1439 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001440 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001441}
1442
Jackal Guof9696682018-10-05 12:23:23 +08001443static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1444 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1445 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001446 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1447 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1448 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001449
1450 return args;
1451}
1452
chaviwd1c23182019-12-20 18:44:56 -08001453static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1454 const std::vector<PointF>& points) {
1455 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001456 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1457 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1458 }
1459
chaviwd1c23182019-12-20 18:44:56 -08001460 PointerProperties pointerProperties[pointerCount];
1461 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001462
chaviwd1c23182019-12-20 18:44:56 -08001463 for (size_t i = 0; i < pointerCount; i++) {
1464 pointerProperties[i].clear();
1465 pointerProperties[i].id = i;
1466 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001467
chaviwd1c23182019-12-20 18:44:56 -08001468 pointerCoords[i].clear();
1469 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1470 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1471 }
Jackal Guof9696682018-10-05 12:23:23 +08001472
1473 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1474 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001475 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001476 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1477 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001478 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1479 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001480 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1481 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001482
1483 return args;
1484}
1485
chaviwd1c23182019-12-20 18:44:56 -08001486static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1487 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1488}
1489
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001490static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1491 const PointerCaptureRequest& request) {
1492 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001493}
1494
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001495/**
1496 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1497 * broken channel.
1498 */
1499TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1500 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1501 sp<FakeWindowHandle> window =
1502 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1503 ADISPLAY_ID_DEFAULT);
1504
1505 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1506
1507 // Window closes its channel, but the window remains.
1508 window->destroyReceiver();
1509 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1510}
1511
Arthur Hungb92218b2018-08-14 12:00:21 +08001512TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001513 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001514 sp<FakeWindowHandle> window =
1515 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001516
Arthur Hung72d8dc32020-03-28 00:48:39 +00001517 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001518 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1519 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1520 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001521
1522 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001523 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001524}
1525
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001526TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1527 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1528 sp<FakeWindowHandle> window =
1529 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1530
1531 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1532 // Inject a MotionEvent to an unknown display.
1533 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1534 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1535 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1536
1537 // Window should receive motion event.
1538 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1539}
1540
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001541/**
1542 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1543 * To ensure that window receives only events that were directly inside of it, add
1544 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1545 * when finding touched windows.
1546 * This test serves as a sanity check for the next test, where setInputWindows is
1547 * called twice.
1548 */
1549TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001550 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001551 sp<FakeWindowHandle> window =
1552 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1553 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001554 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001555
1556 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001557 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001558 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1559 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001560 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001561
1562 // Window should receive motion event.
1563 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1564}
1565
1566/**
1567 * Calling setInputWindows twice, with the same info, should not cause any issues.
1568 * To ensure that window receives only events that were directly inside of it, add
1569 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1570 * when finding touched windows.
1571 */
1572TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001573 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001574 sp<FakeWindowHandle> window =
1575 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1576 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001577 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001578
1579 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1580 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001581 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001582 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1583 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001584 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001585
1586 // Window should receive motion event.
1587 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1588}
1589
Arthur Hungb92218b2018-08-14 12:00:21 +08001590// The foreground window should receive the first touch down event.
1591TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001592 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001593 sp<FakeWindowHandle> windowTop =
1594 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1595 sp<FakeWindowHandle> windowSecond =
1596 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001597
Arthur Hung72d8dc32020-03-28 00:48:39 +00001598 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001599 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1600 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1601 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001602
1603 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001604 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001605 windowSecond->assertNoEvents();
1606}
1607
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001608/**
1609 * Two windows: A top window, and a wallpaper behind the window.
1610 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1611 * gets ACTION_CANCEL.
1612 * 1. foregroundWindow <-- has wallpaper (hasWallpaper=true)
1613 * 2. wallpaperWindow <-- is wallpaper (type=InputWindowInfo::Type::WALLPAPER)
1614 */
1615TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1616 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1617 sp<FakeWindowHandle> foregroundWindow =
1618 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1619 foregroundWindow->setHasWallpaper(true);
1620 sp<FakeWindowHandle> wallpaperWindow =
1621 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1622 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1623 constexpr int expectedWallpaperFlags =
1624 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1625
1626 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1627 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1628 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1629 {100, 200}))
1630 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1631
1632 // Both foreground window and its wallpaper should receive the touch down
1633 foregroundWindow->consumeMotionDown();
1634 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1635
1636 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1637 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1638 ADISPLAY_ID_DEFAULT, {110, 200}))
1639 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1640
1641 foregroundWindow->consumeMotionMove();
1642 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1643
1644 // Now the foreground window goes away, but the wallpaper stays
1645 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1646 foregroundWindow->consumeMotionCancel();
1647 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1648 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1649}
1650
1651/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001652 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1653 * with the following differences:
1654 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1655 * clean up the connection.
1656 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1657 * Ensure that there's no crash in the dispatcher.
1658 */
1659TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1660 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1661 sp<FakeWindowHandle> foregroundWindow =
1662 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1663 foregroundWindow->setHasWallpaper(true);
1664 sp<FakeWindowHandle> wallpaperWindow =
1665 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1666 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1667 constexpr int expectedWallpaperFlags =
1668 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1669
1670 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1671 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1672 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1673 {100, 200}))
1674 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1675
1676 // Both foreground window and its wallpaper should receive the touch down
1677 foregroundWindow->consumeMotionDown();
1678 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1679
1680 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1681 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1682 ADISPLAY_ID_DEFAULT, {110, 200}))
1683 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1684
1685 foregroundWindow->consumeMotionMove();
1686 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1687
1688 // Wallpaper closes its channel, but the window remains.
1689 wallpaperWindow->destroyReceiver();
1690 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1691
1692 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1693 // is no longer valid.
1694 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1695 foregroundWindow->consumeMotionCancel();
1696}
1697
1698/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001699 * A single window that receives touch (on top), and a wallpaper window underneath it.
1700 * The top window gets a multitouch gesture.
1701 * Ensure that wallpaper gets the same gesture.
1702 */
1703TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1704 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1705 sp<FakeWindowHandle> window =
1706 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1707 window->setHasWallpaper(true);
1708
1709 sp<FakeWindowHandle> wallpaperWindow =
1710 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1711 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1712 constexpr int expectedWallpaperFlags =
1713 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1714
1715 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1716
1717 // Touch down on top window
1718 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1719 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1720 {100, 100}))
1721 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1722
1723 // Both top window and its wallpaper should receive the touch down
1724 window->consumeMotionDown();
1725 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1726
1727 // Second finger down on the top window
1728 const MotionEvent secondFingerDownEvent =
1729 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1730 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1731 AINPUT_SOURCE_TOUCHSCREEN)
1732 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1733 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1734 .x(100)
1735 .y(100))
1736 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1737 .x(150)
1738 .y(150))
1739 .build();
1740 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1741 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1742 InputEventInjectionSync::WAIT_FOR_RESULT))
1743 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1744
1745 window->consumeMotionPointerDown(1 /* pointerIndex */);
1746 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1747 expectedWallpaperFlags);
1748 window->assertNoEvents();
1749 wallpaperWindow->assertNoEvents();
1750}
1751
1752/**
1753 * Two windows: a window on the left and window on the right.
1754 * A third window, wallpaper, is behind both windows, and spans both top windows.
1755 * The first touch down goes to the left window. A second pointer touches down on the right window.
1756 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1757 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1758 * ACTION_POINTER_DOWN(1).
1759 */
1760TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1761 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1762 sp<FakeWindowHandle> leftWindow =
1763 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1764 leftWindow->setFrame(Rect(0, 0, 200, 200));
1765 leftWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1766 leftWindow->setHasWallpaper(true);
1767
1768 sp<FakeWindowHandle> rightWindow =
1769 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1770 rightWindow->setFrame(Rect(200, 0, 400, 200));
1771 rightWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1772 rightWindow->setHasWallpaper(true);
1773
1774 sp<FakeWindowHandle> wallpaperWindow =
1775 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1776 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
1777 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1778 constexpr int expectedWallpaperFlags =
1779 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1780
1781 mDispatcher->setInputWindows(
1782 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1783
1784 // Touch down on left window
1785 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1786 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1787 {100, 100}))
1788 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1789
1790 // Both foreground window and its wallpaper should receive the touch down
1791 leftWindow->consumeMotionDown();
1792 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1793
1794 // Second finger down on the right window
1795 const MotionEvent secondFingerDownEvent =
1796 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1797 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1798 AINPUT_SOURCE_TOUCHSCREEN)
1799 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1800 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1801 .x(100)
1802 .y(100))
1803 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1804 .x(300)
1805 .y(100))
1806 .build();
1807 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1808 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1809 InputEventInjectionSync::WAIT_FOR_RESULT))
1810 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1811
1812 leftWindow->consumeMotionMove();
1813 // Since the touch is split, right window gets ACTION_DOWN
1814 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1815 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1816 expectedWallpaperFlags);
1817
1818 // Now, leftWindow, which received the first finger, disappears.
1819 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1820 leftWindow->consumeMotionCancel();
1821 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1822 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1823
1824 // The pointer that's still down on the right window moves, and goes to the right window only.
1825 // As far as the dispatcher's concerned though, both pointers are still present.
1826 const MotionEvent secondFingerMoveEvent =
1827 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1828 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1829 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1830 .x(100)
1831 .y(100))
1832 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1833 .x(310)
1834 .y(110))
1835 .build();
1836 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1837 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1838 InputEventInjectionSync::WAIT_FOR_RESULT));
1839 rightWindow->consumeMotionMove();
1840
1841 leftWindow->assertNoEvents();
1842 rightWindow->assertNoEvents();
1843 wallpaperWindow->assertNoEvents();
1844}
1845
Garfield Tandf26e862020-07-01 20:18:19 -07001846TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001847 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001848 sp<FakeWindowHandle> windowLeft =
1849 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1850 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001851 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001852 sp<FakeWindowHandle> windowRight =
1853 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1854 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001855 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001856
1857 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1858
1859 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1860
1861 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001862 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001863 injectMotionEvent(mDispatcher,
1864 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1865 AINPUT_SOURCE_MOUSE)
1866 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1867 .x(900)
1868 .y(400))
1869 .build()));
1870 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1871 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1872 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1873 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1874
1875 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001876 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001877 injectMotionEvent(mDispatcher,
1878 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1879 AINPUT_SOURCE_MOUSE)
1880 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1881 .x(300)
1882 .y(400))
1883 .build()));
1884 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1885 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1886 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1887 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1888 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1889 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1890
1891 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001892 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001893 injectMotionEvent(mDispatcher,
1894 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1895 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1896 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1897 .x(300)
1898 .y(400))
1899 .build()));
1900 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1901
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001902 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001903 injectMotionEvent(mDispatcher,
1904 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1905 AINPUT_SOURCE_MOUSE)
1906 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1907 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1908 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1909 .x(300)
1910 .y(400))
1911 .build()));
1912 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1913 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1914
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001915 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001916 injectMotionEvent(mDispatcher,
1917 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1918 AINPUT_SOURCE_MOUSE)
1919 .buttonState(0)
1920 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1921 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1922 .x(300)
1923 .y(400))
1924 .build()));
1925 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1926 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1927
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001928 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001929 injectMotionEvent(mDispatcher,
1930 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1931 .buttonState(0)
1932 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1933 .x(300)
1934 .y(400))
1935 .build()));
1936 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1937
1938 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001939 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001940 injectMotionEvent(mDispatcher,
1941 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1942 AINPUT_SOURCE_MOUSE)
1943 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1944 .x(900)
1945 .y(400))
1946 .build()));
1947 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1948 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1949 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1950 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1951 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1952 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1953}
1954
1955// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1956// directly in this test.
1957TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001958 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001959 sp<FakeWindowHandle> window =
1960 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1961 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001962 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001963
1964 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1965
1966 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1967
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001968 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001969 injectMotionEvent(mDispatcher,
1970 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1971 AINPUT_SOURCE_MOUSE)
1972 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1973 .x(300)
1974 .y(400))
1975 .build()));
1976 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1977 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1978
1979 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001980 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001981 injectMotionEvent(mDispatcher,
1982 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1983 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1984 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1985 .x(300)
1986 .y(400))
1987 .build()));
1988 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1989
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001990 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001991 injectMotionEvent(mDispatcher,
1992 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1993 AINPUT_SOURCE_MOUSE)
1994 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1995 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1996 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1997 .x(300)
1998 .y(400))
1999 .build()));
2000 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2001 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2002
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002003 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002004 injectMotionEvent(mDispatcher,
2005 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2006 AINPUT_SOURCE_MOUSE)
2007 .buttonState(0)
2008 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2009 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2010 .x(300)
2011 .y(400))
2012 .build()));
2013 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2014 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2015
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002016 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002017 injectMotionEvent(mDispatcher,
2018 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2019 .buttonState(0)
2020 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2021 .x(300)
2022 .y(400))
2023 .build()));
2024 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2025
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002026 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002027 injectMotionEvent(mDispatcher,
2028 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2029 AINPUT_SOURCE_MOUSE)
2030 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2031 .x(300)
2032 .y(400))
2033 .build()));
2034 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2035 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2036}
2037
Garfield Tan00f511d2019-06-12 16:55:40 -07002038TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002039 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002040
2041 sp<FakeWindowHandle> windowLeft =
2042 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2043 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002044 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002045 sp<FakeWindowHandle> windowRight =
2046 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2047 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05002048 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002049
2050 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2051
Arthur Hung72d8dc32020-03-28 00:48:39 +00002052 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002053
2054 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2055 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002056 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002057 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002058 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002059 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002060 windowRight->assertNoEvents();
2061}
2062
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002063TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002064 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002065 sp<FakeWindowHandle> window =
2066 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002067 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002068
Arthur Hung72d8dc32020-03-28 00:48:39 +00002069 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002070 setFocusedWindow(window);
2071
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002072 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002073
2074 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2075 mDispatcher->notifyKey(&keyArgs);
2076
2077 // Window should receive key down event.
2078 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2079
2080 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2081 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002082 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002083 mDispatcher->notifyDeviceReset(&args);
2084 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2085 AKEY_EVENT_FLAG_CANCELED);
2086}
2087
2088TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002089 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002090 sp<FakeWindowHandle> window =
2091 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2092
Arthur Hung72d8dc32020-03-28 00:48:39 +00002093 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002094
2095 NotifyMotionArgs motionArgs =
2096 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2097 ADISPLAY_ID_DEFAULT);
2098 mDispatcher->notifyMotion(&motionArgs);
2099
2100 // Window should receive motion down event.
2101 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2102
2103 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2104 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002105 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002106 mDispatcher->notifyDeviceReset(&args);
2107 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2108 0 /*expectedFlags*/);
2109}
2110
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002111/**
2112 * Ensure the correct coordinate spaces are used by InputDispatcher.
2113 *
2114 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2115 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2116 * space.
2117 */
2118class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2119public:
2120 void SetUp() override {
2121 InputDispatcherTest::SetUp();
2122 mDisplayInfos.clear();
2123 mWindowInfos.clear();
2124 }
2125
2126 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2127 gui::DisplayInfo info;
2128 info.displayId = displayId;
2129 info.transform = transform;
2130 mDisplayInfos.push_back(std::move(info));
2131 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2132 }
2133
2134 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2135 mWindowInfos.push_back(*windowHandle->getInfo());
2136 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2137 }
2138
2139 // Set up a test scenario where the display has a scaled projection and there are two windows
2140 // on the display.
2141 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2142 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2143 // respectively.
2144 ui::Transform displayTransform;
2145 displayTransform.set(2, 0, 0, 4);
2146 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2147
2148 std::shared_ptr<FakeApplicationHandle> application =
2149 std::make_shared<FakeApplicationHandle>();
2150
2151 // Add two windows to the display. Their frames are represented in the display space.
2152 sp<FakeWindowHandle> firstWindow =
2153 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2154 firstWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2155 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2156 addWindow(firstWindow);
2157
2158 sp<FakeWindowHandle> secondWindow =
2159 new FakeWindowHandle(application, mDispatcher, "Second Window",
2160 ADISPLAY_ID_DEFAULT);
2161 secondWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2162 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2163 addWindow(secondWindow);
2164 return {std::move(firstWindow), std::move(secondWindow)};
2165 }
2166
2167private:
2168 std::vector<gui::DisplayInfo> mDisplayInfos;
2169 std::vector<gui::WindowInfo> mWindowInfos;
2170};
2171
2172TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2173 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2174 // Send down to the first window. The point is represented in the display space. The point is
2175 // selected so that if the hit test was done with the transform applied to it, then it would
2176 // end up in the incorrect window.
2177 NotifyMotionArgs downMotionArgs =
2178 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2179 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2180 mDispatcher->notifyMotion(&downMotionArgs);
2181
2182 firstWindow->consumeMotionDown();
2183 secondWindow->assertNoEvents();
2184}
2185
2186// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2187// the event should be treated as being in the logical display space.
2188TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2189 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2190 // Send down to the first window. The point is represented in the logical display space. The
2191 // point is selected so that if the hit test was done in logical display space, then it would
2192 // end up in the incorrect window.
2193 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2194 PointF{75 * 2, 55 * 4});
2195
2196 firstWindow->consumeMotionDown();
2197 secondWindow->assertNoEvents();
2198}
2199
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002200// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2201// event should be treated as being in the logical display space.
2202TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2203 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2204
2205 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2206 ui::Transform injectedEventTransform;
2207 injectedEventTransform.set(matrix);
2208 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2209 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2210
2211 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2212 .displayId(ADISPLAY_ID_DEFAULT)
2213 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2214 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2215 .x(untransformedPoint.x)
2216 .y(untransformedPoint.y))
2217 .build();
2218 event.transform(matrix);
2219
2220 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2221 InputEventInjectionSync::WAIT_FOR_RESULT);
2222
2223 firstWindow->consumeMotionDown();
2224 secondWindow->assertNoEvents();
2225}
2226
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002227TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2228 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2229
2230 // Send down to the second window.
2231 NotifyMotionArgs downMotionArgs =
2232 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2233 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2234 mDispatcher->notifyMotion(&downMotionArgs);
2235
2236 firstWindow->assertNoEvents();
2237 const MotionEvent* event = secondWindow->consumeMotion();
2238 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2239
2240 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2241 EXPECT_EQ(300, event->getRawX(0));
2242 EXPECT_EQ(880, event->getRawY(0));
2243
2244 // Ensure that the x and y values are in the window's coordinate space.
2245 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2246 // the logical display space. This will be the origin of the window space.
2247 EXPECT_EQ(100, event->getX(0));
2248 EXPECT_EQ(80, event->getY(0));
2249}
2250
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002251using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2252 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002253
2254class TransferTouchFixture : public InputDispatcherTest,
2255 public ::testing::WithParamInterface<TransferFunction> {};
2256
2257TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002258 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002259
2260 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002261 sp<FakeWindowHandle> firstWindow =
2262 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2263 sp<FakeWindowHandle> secondWindow =
2264 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002265
2266 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002267 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002268
2269 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002270 NotifyMotionArgs downMotionArgs =
2271 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2272 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002273 mDispatcher->notifyMotion(&downMotionArgs);
2274 // Only the first window should get the down event
2275 firstWindow->consumeMotionDown();
2276 secondWindow->assertNoEvents();
2277
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002278 // Transfer touch to the second window
2279 TransferFunction f = GetParam();
2280 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2281 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002282 // The first window gets cancel and the second gets down
2283 firstWindow->consumeMotionCancel();
2284 secondWindow->consumeMotionDown();
2285
2286 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002287 NotifyMotionArgs upMotionArgs =
2288 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2289 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002290 mDispatcher->notifyMotion(&upMotionArgs);
2291 // The first window gets no events and the second gets up
2292 firstWindow->assertNoEvents();
2293 secondWindow->consumeMotionUp();
2294}
2295
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002296TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002297 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002298
2299 PointF touchPoint = {10, 10};
2300
2301 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002302 sp<FakeWindowHandle> firstWindow =
2303 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2304 sp<FakeWindowHandle> secondWindow =
2305 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002306
2307 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002308 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002309
2310 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002311 NotifyMotionArgs downMotionArgs =
2312 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2313 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002314 mDispatcher->notifyMotion(&downMotionArgs);
2315 // Only the first window should get the down event
2316 firstWindow->consumeMotionDown();
2317 secondWindow->assertNoEvents();
2318
2319 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002320 NotifyMotionArgs pointerDownMotionArgs =
2321 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2322 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2323 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2324 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002325 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2326 // Only the first window should get the pointer down event
2327 firstWindow->consumeMotionPointerDown(1);
2328 secondWindow->assertNoEvents();
2329
2330 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002331 TransferFunction f = GetParam();
2332 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2333 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002334 // The first window gets cancel and the second gets down and pointer down
2335 firstWindow->consumeMotionCancel();
2336 secondWindow->consumeMotionDown();
2337 secondWindow->consumeMotionPointerDown(1);
2338
2339 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002340 NotifyMotionArgs pointerUpMotionArgs =
2341 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2342 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2343 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2344 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002345 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2346 // The first window gets nothing and the second gets pointer up
2347 firstWindow->assertNoEvents();
2348 secondWindow->consumeMotionPointerUp(1);
2349
2350 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002351 NotifyMotionArgs upMotionArgs =
2352 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2353 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002354 mDispatcher->notifyMotion(&upMotionArgs);
2355 // The first window gets nothing and the second gets up
2356 firstWindow->assertNoEvents();
2357 secondWindow->consumeMotionUp();
2358}
2359
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002360// For the cases of single pointer touch and two pointers non-split touch, the api's
2361// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2362// for the case where there are multiple pointers split across several windows.
2363INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2364 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002365 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2366 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002367 return dispatcher->transferTouch(destChannelToken);
2368 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002369 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2370 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002371 return dispatcher->transferTouchFocus(from, to,
2372 false /*isDragAndDrop*/);
2373 }));
2374
Svet Ganov5d3bc372020-01-26 23:11:07 -08002375TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002376 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002377
2378 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002379 sp<FakeWindowHandle> firstWindow =
2380 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002381 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002382 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002383
2384 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002385 sp<FakeWindowHandle> secondWindow =
2386 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002387 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002388 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002389
2390 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002391 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002392
2393 PointF pointInFirst = {300, 200};
2394 PointF pointInSecond = {300, 600};
2395
2396 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002397 NotifyMotionArgs firstDownMotionArgs =
2398 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2399 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002400 mDispatcher->notifyMotion(&firstDownMotionArgs);
2401 // Only the first window should get the down event
2402 firstWindow->consumeMotionDown();
2403 secondWindow->assertNoEvents();
2404
2405 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002406 NotifyMotionArgs secondDownMotionArgs =
2407 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2408 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2409 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2410 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002411 mDispatcher->notifyMotion(&secondDownMotionArgs);
2412 // The first window gets a move and the second a down
2413 firstWindow->consumeMotionMove();
2414 secondWindow->consumeMotionDown();
2415
2416 // Transfer touch focus to the second window
2417 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2418 // The first window gets cancel and the new gets pointer down (it already saw down)
2419 firstWindow->consumeMotionCancel();
2420 secondWindow->consumeMotionPointerDown(1);
2421
2422 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002423 NotifyMotionArgs pointerUpMotionArgs =
2424 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2425 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2426 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2427 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002428 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2429 // The first window gets nothing and the second gets pointer up
2430 firstWindow->assertNoEvents();
2431 secondWindow->consumeMotionPointerUp(1);
2432
2433 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002434 NotifyMotionArgs upMotionArgs =
2435 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2436 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002437 mDispatcher->notifyMotion(&upMotionArgs);
2438 // The first window gets nothing and the second gets up
2439 firstWindow->assertNoEvents();
2440 secondWindow->consumeMotionUp();
2441}
2442
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002443// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2444// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2445// touch is not supported, so the touch should continue on those windows and the transferred-to
2446// window should get nothing.
2447TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2448 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2449
2450 // Create a non touch modal window that supports split touch
2451 sp<FakeWindowHandle> firstWindow =
2452 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2453 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002454 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002455
2456 // Create a non touch modal window that supports split touch
2457 sp<FakeWindowHandle> secondWindow =
2458 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2459 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002460 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002461
2462 // Add the windows to the dispatcher
2463 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2464
2465 PointF pointInFirst = {300, 200};
2466 PointF pointInSecond = {300, 600};
2467
2468 // Send down to the first window
2469 NotifyMotionArgs firstDownMotionArgs =
2470 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2471 ADISPLAY_ID_DEFAULT, {pointInFirst});
2472 mDispatcher->notifyMotion(&firstDownMotionArgs);
2473 // Only the first window should get the down event
2474 firstWindow->consumeMotionDown();
2475 secondWindow->assertNoEvents();
2476
2477 // Send down to the second window
2478 NotifyMotionArgs secondDownMotionArgs =
2479 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2480 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2481 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2482 {pointInFirst, pointInSecond});
2483 mDispatcher->notifyMotion(&secondDownMotionArgs);
2484 // The first window gets a move and the second a down
2485 firstWindow->consumeMotionMove();
2486 secondWindow->consumeMotionDown();
2487
2488 // Transfer touch focus to the second window
2489 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2490 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2491 ASSERT_FALSE(transferred);
2492 firstWindow->assertNoEvents();
2493 secondWindow->assertNoEvents();
2494
2495 // The rest of the dispatch should proceed as normal
2496 // Send pointer up to the second window
2497 NotifyMotionArgs pointerUpMotionArgs =
2498 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2499 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2500 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2501 {pointInFirst, pointInSecond});
2502 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2503 // The first window gets MOVE and the second gets pointer up
2504 firstWindow->consumeMotionMove();
2505 secondWindow->consumeMotionUp();
2506
2507 // Send up event to the first window
2508 NotifyMotionArgs upMotionArgs =
2509 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2510 ADISPLAY_ID_DEFAULT);
2511 mDispatcher->notifyMotion(&upMotionArgs);
2512 // The first window gets nothing and the second gets up
2513 firstWindow->consumeMotionUp();
2514 secondWindow->assertNoEvents();
2515}
2516
Arthur Hungabbb9d82021-09-01 14:52:30 +00002517// This case will create two windows and one mirrored window on the default display and mirror
2518// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2519// the windows info of second display before default display.
2520TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2521 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2522 sp<FakeWindowHandle> firstWindowInPrimary =
2523 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2524 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2525 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2526 sp<FakeWindowHandle> secondWindowInPrimary =
2527 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2528 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2529 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2530
2531 sp<FakeWindowHandle> mirrorWindowInPrimary =
2532 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2533 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2534 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2535
2536 sp<FakeWindowHandle> firstWindowInSecondary =
2537 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2538 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2539 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2540
2541 sp<FakeWindowHandle> secondWindowInSecondary =
2542 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2543 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2544 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2545
2546 // Update window info, let it find window handle of second display first.
2547 mDispatcher->setInputWindows(
2548 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2549 {ADISPLAY_ID_DEFAULT,
2550 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2551
2552 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2553 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2554 {50, 50}))
2555 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2556
2557 // Window should receive motion event.
2558 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2559
2560 // Transfer touch focus
2561 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2562 secondWindowInPrimary->getToken()));
2563 // The first window gets cancel.
2564 firstWindowInPrimary->consumeMotionCancel();
2565 secondWindowInPrimary->consumeMotionDown();
2566
2567 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2568 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2569 ADISPLAY_ID_DEFAULT, {150, 50}))
2570 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2571 firstWindowInPrimary->assertNoEvents();
2572 secondWindowInPrimary->consumeMotionMove();
2573
2574 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2575 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2576 {150, 50}))
2577 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2578 firstWindowInPrimary->assertNoEvents();
2579 secondWindowInPrimary->consumeMotionUp();
2580}
2581
2582// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2583// 'transferTouch' api.
2584TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2585 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2586 sp<FakeWindowHandle> firstWindowInPrimary =
2587 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2588 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2589 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2590 sp<FakeWindowHandle> secondWindowInPrimary =
2591 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2592 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2593 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2594
2595 sp<FakeWindowHandle> mirrorWindowInPrimary =
2596 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2597 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2598 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2599
2600 sp<FakeWindowHandle> firstWindowInSecondary =
2601 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2602 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2603 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2604
2605 sp<FakeWindowHandle> secondWindowInSecondary =
2606 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2607 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2608 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2609
2610 // Update window info, let it find window handle of second display first.
2611 mDispatcher->setInputWindows(
2612 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2613 {ADISPLAY_ID_DEFAULT,
2614 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2615
2616 // Touch on second display.
2617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2618 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2619 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2620
2621 // Window should receive motion event.
2622 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2623
2624 // Transfer touch focus
2625 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2626
2627 // The first window gets cancel.
2628 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2629 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2630
2631 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2632 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2633 SECOND_DISPLAY_ID, {150, 50}))
2634 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2635 firstWindowInPrimary->assertNoEvents();
2636 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2637
2638 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2639 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2640 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2641 firstWindowInPrimary->assertNoEvents();
2642 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2643}
2644
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002645TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002646 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002647 sp<FakeWindowHandle> window =
2648 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2649
Vishnu Nair47074b82020-08-14 11:54:47 -07002650 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002651 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002652 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002653
2654 window->consumeFocusEvent(true);
2655
2656 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2657 mDispatcher->notifyKey(&keyArgs);
2658
2659 // Window should receive key down event.
2660 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2661}
2662
2663TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002664 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002665 sp<FakeWindowHandle> window =
2666 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2667
Arthur Hung72d8dc32020-03-28 00:48:39 +00002668 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002669
2670 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2671 mDispatcher->notifyKey(&keyArgs);
2672 mDispatcher->waitForIdle();
2673
2674 window->assertNoEvents();
2675}
2676
2677// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2678TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002679 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002680 sp<FakeWindowHandle> window =
2681 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2682
Arthur Hung72d8dc32020-03-28 00:48:39 +00002683 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002684
2685 // Send key
2686 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2687 mDispatcher->notifyKey(&keyArgs);
2688 // Send motion
2689 NotifyMotionArgs motionArgs =
2690 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2691 ADISPLAY_ID_DEFAULT);
2692 mDispatcher->notifyMotion(&motionArgs);
2693
2694 // Window should receive only the motion event
2695 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2696 window->assertNoEvents(); // Key event or focus event will not be received
2697}
2698
arthurhungea3f4fc2020-12-21 23:18:53 +08002699TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2700 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2701
2702 // Create first non touch modal window that supports split touch
2703 sp<FakeWindowHandle> firstWindow =
2704 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2705 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002706 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002707
2708 // Create second non touch modal window that supports split touch
2709 sp<FakeWindowHandle> secondWindow =
2710 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2711 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002712 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002713
2714 // Add the windows to the dispatcher
2715 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2716
2717 PointF pointInFirst = {300, 200};
2718 PointF pointInSecond = {300, 600};
2719
2720 // Send down to the first window
2721 NotifyMotionArgs firstDownMotionArgs =
2722 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2723 ADISPLAY_ID_DEFAULT, {pointInFirst});
2724 mDispatcher->notifyMotion(&firstDownMotionArgs);
2725 // Only the first window should get the down event
2726 firstWindow->consumeMotionDown();
2727 secondWindow->assertNoEvents();
2728
2729 // Send down to the second window
2730 NotifyMotionArgs secondDownMotionArgs =
2731 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2732 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2733 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2734 {pointInFirst, pointInSecond});
2735 mDispatcher->notifyMotion(&secondDownMotionArgs);
2736 // The first window gets a move and the second a down
2737 firstWindow->consumeMotionMove();
2738 secondWindow->consumeMotionDown();
2739
2740 // Send pointer cancel to the second window
2741 NotifyMotionArgs pointerUpMotionArgs =
2742 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2743 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2744 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2745 {pointInFirst, pointInSecond});
2746 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2747 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2748 // The first window gets move and the second gets cancel.
2749 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2750 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2751
2752 // Send up event.
2753 NotifyMotionArgs upMotionArgs =
2754 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2755 ADISPLAY_ID_DEFAULT);
2756 mDispatcher->notifyMotion(&upMotionArgs);
2757 // The first window gets up and the second gets nothing.
2758 firstWindow->consumeMotionUp();
2759 secondWindow->assertNoEvents();
2760}
2761
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002762TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2763 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2764
2765 sp<FakeWindowHandle> window =
2766 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2767 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2768 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2769 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2770 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2771
2772 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2773 window->assertNoEvents();
2774 mDispatcher->waitForIdle();
2775}
2776
chaviwd1c23182019-12-20 18:44:56 -08002777class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002778public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002779 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002780 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07002781 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002782 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002783 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002784 }
2785
chaviwd1c23182019-12-20 18:44:56 -08002786 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2787
2788 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2789 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2790 expectedDisplayId, expectedFlags);
2791 }
2792
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002793 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2794
2795 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2796
chaviwd1c23182019-12-20 18:44:56 -08002797 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2798 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2799 expectedDisplayId, expectedFlags);
2800 }
2801
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002802 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2803 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2804 expectedDisplayId, expectedFlags);
2805 }
2806
chaviwd1c23182019-12-20 18:44:56 -08002807 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2808 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2809 expectedDisplayId, expectedFlags);
2810 }
2811
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002812 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2813 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2814 expectedDisplayId, expectedFlags);
2815 }
2816
Arthur Hungfbfa5722021-11-16 02:45:54 +00002817 void consumeMotionPointerDown(int32_t pointerIdx) {
2818 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2819 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2820 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2821 0 /*expectedFlags*/);
2822 }
2823
Evan Rosky84f07f02021-04-16 10:42:42 -07002824 MotionEvent* consumeMotion() {
2825 InputEvent* event = mInputReceiver->consume();
2826 if (!event) {
2827 ADD_FAILURE() << "No event was produced";
2828 return nullptr;
2829 }
2830 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2831 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2832 return nullptr;
2833 }
2834 return static_cast<MotionEvent*>(event);
2835 }
2836
chaviwd1c23182019-12-20 18:44:56 -08002837 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2838
2839private:
2840 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002841};
2842
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002843using InputDispatcherMonitorTest = InputDispatcherTest;
2844
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002845/**
2846 * Two entities that receive touch: A window, and a global monitor.
2847 * The touch goes to the window, and then the window disappears.
2848 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2849 * for the monitor, as well.
2850 * 1. foregroundWindow
2851 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2852 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002853TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002854 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2855 sp<FakeWindowHandle> window =
2856 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2857
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002858 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002859
2860 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2861 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2862 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2863 {100, 200}))
2864 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2865
2866 // Both the foreground window and the global monitor should receive the touch down
2867 window->consumeMotionDown();
2868 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2869
2870 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2871 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2872 ADISPLAY_ID_DEFAULT, {110, 200}))
2873 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2874
2875 window->consumeMotionMove();
2876 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2877
2878 // Now the foreground window goes away
2879 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2880 window->consumeMotionCancel();
2881 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2882
2883 // If more events come in, there will be no more foreground window to send them to. This will
2884 // cause a cancel for the monitor, as well.
2885 ASSERT_EQ(InputEventInjectionResult::FAILED,
2886 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2887 ADISPLAY_ID_DEFAULT, {120, 200}))
2888 << "Injection should fail because the window was removed";
2889 window->assertNoEvents();
2890 // Global monitor now gets the cancel
2891 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2892}
2893
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002894TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002895 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002896 sp<FakeWindowHandle> window =
2897 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002898 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002899
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002900 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002901
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002902 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002903 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002904 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002905 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002906 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002907}
2908
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002909TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
2910 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002911
Chris Yea209fde2020-07-22 13:54:51 -07002912 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002913 sp<FakeWindowHandle> window =
2914 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002915 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002916
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002917 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002918 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002919 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002920 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002921 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002922
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002923 // Pilfer pointers from the monitor.
2924 // This should not do anything and the window should continue to receive events.
2925 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00002926
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002927 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002928 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2929 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002930 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002931
2932 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2933 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002934}
2935
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002936TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07002937 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2938 sp<FakeWindowHandle> window =
2939 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2940 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2941 window->setWindowOffset(20, 40);
2942 window->setWindowTransform(0, 1, -1, 0);
2943
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002944 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07002945
2946 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2947 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2948 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2949 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2950 MotionEvent* event = monitor.consumeMotion();
2951 // Even though window has transform, gesture monitor must not.
2952 ASSERT_EQ(ui::Transform(), event->getTransform());
2953}
2954
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002955TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002956 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002957 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00002958
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002959 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00002960 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002961 << "Injection should fail if there is a monitor, but no touchable window";
2962 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00002963}
2964
chaviw81e2bb92019-12-18 15:03:51 -08002965TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002966 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002967 sp<FakeWindowHandle> window =
2968 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2969
Arthur Hung72d8dc32020-03-28 00:48:39 +00002970 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002971
2972 NotifyMotionArgs motionArgs =
2973 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2974 ADISPLAY_ID_DEFAULT);
2975
2976 mDispatcher->notifyMotion(&motionArgs);
2977 // Window should receive motion down event.
2978 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2979
2980 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002981 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002982 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2983 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2984 motionArgs.pointerCoords[0].getX() - 10);
2985
2986 mDispatcher->notifyMotion(&motionArgs);
2987 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2988 0 /*expectedFlags*/);
2989}
2990
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002991/**
2992 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2993 * the device default right away. In the test scenario, we check both the default value,
2994 * and the action of enabling / disabling.
2995 */
2996TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002997 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002998 sp<FakeWindowHandle> window =
2999 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3000
3001 // Set focused application.
3002 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003003 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003004
3005 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003006 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003007 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003008 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3009
3010 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003011 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003012 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003013 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3014
3015 SCOPED_TRACE("Disable touch mode");
3016 mDispatcher->setInTouchMode(false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003017 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003018 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003019 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003020 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003021 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3022
3023 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003024 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003025 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003026 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3027
3028 SCOPED_TRACE("Enable touch mode again");
3029 mDispatcher->setInTouchMode(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003030 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003031 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003032 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003033 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003034 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3035
3036 window->assertNoEvents();
3037}
3038
Gang Wange9087892020-01-07 12:17:14 -05003039TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003040 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003041 sp<FakeWindowHandle> window =
3042 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3043
3044 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003045 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003046
Arthur Hung72d8dc32020-03-28 00:48:39 +00003047 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003048 setFocusedWindow(window);
3049
Gang Wange9087892020-01-07 12:17:14 -05003050 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3051
3052 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3053 mDispatcher->notifyKey(&keyArgs);
3054
3055 InputEvent* event = window->consume();
3056 ASSERT_NE(event, nullptr);
3057
3058 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3059 ASSERT_NE(verified, nullptr);
3060 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3061
3062 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3063 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3064 ASSERT_EQ(keyArgs.source, verified->source);
3065 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3066
3067 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3068
3069 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003070 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003071 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003072 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3073 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3074 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3075 ASSERT_EQ(0, verifiedKey.repeatCount);
3076}
3077
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003078TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003079 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003080 sp<FakeWindowHandle> window =
3081 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3082
3083 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3084
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003085 ui::Transform transform;
3086 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3087
3088 gui::DisplayInfo displayInfo;
3089 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3090 displayInfo.transform = transform;
3091
3092 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003093
3094 NotifyMotionArgs motionArgs =
3095 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3096 ADISPLAY_ID_DEFAULT);
3097 mDispatcher->notifyMotion(&motionArgs);
3098
3099 InputEvent* event = window->consume();
3100 ASSERT_NE(event, nullptr);
3101
3102 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3103 ASSERT_NE(verified, nullptr);
3104 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3105
3106 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3107 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3108 EXPECT_EQ(motionArgs.source, verified->source);
3109 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3110
3111 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3112
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003113 const vec2 rawXY =
3114 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3115 motionArgs.pointerCoords[0].getXYValue());
3116 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3117 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003118 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003119 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003120 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003121 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3122 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3123}
3124
chaviw09c8d2d2020-08-24 15:48:26 -07003125/**
3126 * Ensure that separate calls to sign the same data are generating the same key.
3127 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3128 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3129 * tests.
3130 */
3131TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3132 KeyEvent event = getTestKeyEvent();
3133 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3134
3135 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3136 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3137 ASSERT_EQ(hmac1, hmac2);
3138}
3139
3140/**
3141 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3142 */
3143TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3144 KeyEvent event = getTestKeyEvent();
3145 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3146 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3147
3148 verifiedEvent.deviceId += 1;
3149 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3150
3151 verifiedEvent.source += 1;
3152 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3153
3154 verifiedEvent.eventTimeNanos += 1;
3155 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3156
3157 verifiedEvent.displayId += 1;
3158 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3159
3160 verifiedEvent.action += 1;
3161 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3162
3163 verifiedEvent.downTimeNanos += 1;
3164 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3165
3166 verifiedEvent.flags += 1;
3167 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3168
3169 verifiedEvent.keyCode += 1;
3170 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3171
3172 verifiedEvent.scanCode += 1;
3173 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3174
3175 verifiedEvent.metaState += 1;
3176 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3177
3178 verifiedEvent.repeatCount += 1;
3179 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3180}
3181
Vishnu Nair958da932020-08-21 17:12:37 -07003182TEST_F(InputDispatcherTest, SetFocusedWindow) {
3183 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3184 sp<FakeWindowHandle> windowTop =
3185 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3186 sp<FakeWindowHandle> windowSecond =
3187 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3188 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3189
3190 // Top window is also focusable but is not granted focus.
3191 windowTop->setFocusable(true);
3192 windowSecond->setFocusable(true);
3193 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3194 setFocusedWindow(windowSecond);
3195
3196 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003197 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3198 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003199
3200 // Focused window should receive event.
3201 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3202 windowTop->assertNoEvents();
3203}
3204
3205TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3206 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3207 sp<FakeWindowHandle> window =
3208 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3209 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3210
3211 window->setFocusable(true);
3212 // Release channel for window is no longer valid.
3213 window->releaseChannel();
3214 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3215 setFocusedWindow(window);
3216
3217 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003218 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3219 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003220
3221 // window channel is invalid, so it should not receive any input event.
3222 window->assertNoEvents();
3223}
3224
3225TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3226 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3227 sp<FakeWindowHandle> window =
3228 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3229 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3230
3231 // Window is not focusable.
3232 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3233 setFocusedWindow(window);
3234
3235 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003236 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3237 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003238
3239 // window is invalid, so it should not receive any input event.
3240 window->assertNoEvents();
3241}
3242
3243TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3244 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3245 sp<FakeWindowHandle> windowTop =
3246 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3247 sp<FakeWindowHandle> windowSecond =
3248 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3249 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3250
3251 windowTop->setFocusable(true);
3252 windowSecond->setFocusable(true);
3253 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3254 setFocusedWindow(windowTop);
3255 windowTop->consumeFocusEvent(true);
3256
3257 setFocusedWindow(windowSecond, windowTop);
3258 windowSecond->consumeFocusEvent(true);
3259 windowTop->consumeFocusEvent(false);
3260
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003261 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3262 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003263
3264 // Focused window should receive event.
3265 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3266}
3267
3268TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3269 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3270 sp<FakeWindowHandle> windowTop =
3271 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3272 sp<FakeWindowHandle> windowSecond =
3273 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3274 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3275
3276 windowTop->setFocusable(true);
3277 windowSecond->setFocusable(true);
3278 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3279 setFocusedWindow(windowSecond, windowTop);
3280
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003281 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3282 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003283
3284 // Event should be dropped.
3285 windowTop->assertNoEvents();
3286 windowSecond->assertNoEvents();
3287}
3288
3289TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3290 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3291 sp<FakeWindowHandle> window =
3292 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3293 sp<FakeWindowHandle> previousFocusedWindow =
3294 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3295 ADISPLAY_ID_DEFAULT);
3296 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3297
3298 window->setFocusable(true);
3299 previousFocusedWindow->setFocusable(true);
3300 window->setVisible(false);
3301 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3302 setFocusedWindow(previousFocusedWindow);
3303 previousFocusedWindow->consumeFocusEvent(true);
3304
3305 // Requesting focus on invisible window takes focus from currently focused window.
3306 setFocusedWindow(window);
3307 previousFocusedWindow->consumeFocusEvent(false);
3308
3309 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003310 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003311 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003312 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003313
3314 // Window does not get focus event or key down.
3315 window->assertNoEvents();
3316
3317 // Window becomes visible.
3318 window->setVisible(true);
3319 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3320
3321 // Window receives focus event.
3322 window->consumeFocusEvent(true);
3323 // Focused window receives key down.
3324 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3325}
3326
Vishnu Nair599f1412021-06-21 10:39:58 -07003327TEST_F(InputDispatcherTest, DisplayRemoved) {
3328 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3329 sp<FakeWindowHandle> window =
3330 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3331 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3332
3333 // window is granted focus.
3334 window->setFocusable(true);
3335 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3336 setFocusedWindow(window);
3337 window->consumeFocusEvent(true);
3338
3339 // When a display is removed window loses focus.
3340 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3341 window->consumeFocusEvent(false);
3342}
3343
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003344/**
3345 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3346 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3347 * of the 'slipperyEnterWindow'.
3348 *
3349 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3350 * a way so that the touched location is no longer covered by the top window.
3351 *
3352 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3353 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3354 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3355 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3356 * with ACTION_DOWN).
3357 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3358 * window moved itself away from the touched location and had Flag::SLIPPERY.
3359 *
3360 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3361 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3362 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3363 *
3364 * In this test, we ensure that the event received by the bottom window has
3365 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3366 */
3367TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3368 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3369 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3370
3371 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3372 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3373
3374 sp<FakeWindowHandle> slipperyExitWindow =
3375 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003376 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003377 // Make sure this one overlaps the bottom window
3378 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3379 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3380 // one. Windows with the same owner are not considered to be occluding each other.
3381 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3382
3383 sp<FakeWindowHandle> slipperyEnterWindow =
3384 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3385 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3386
3387 mDispatcher->setInputWindows(
3388 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3389
3390 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3391 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3392 ADISPLAY_ID_DEFAULT, {{50, 50}});
3393 mDispatcher->notifyMotion(&args);
3394 slipperyExitWindow->consumeMotionDown();
3395 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3396 mDispatcher->setInputWindows(
3397 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3398
3399 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3400 ADISPLAY_ID_DEFAULT, {{51, 51}});
3401 mDispatcher->notifyMotion(&args);
3402
3403 slipperyExitWindow->consumeMotionCancel();
3404
3405 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3406 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3407}
3408
Garfield Tan1c7bc862020-01-28 13:24:04 -08003409class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3410protected:
3411 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3412 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3413
Chris Yea209fde2020-07-22 13:54:51 -07003414 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003415 sp<FakeWindowHandle> mWindow;
3416
3417 virtual void SetUp() override {
3418 mFakePolicy = new FakeInputDispatcherPolicy();
3419 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003420 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003421 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3422 ASSERT_EQ(OK, mDispatcher->start());
3423
3424 setUpWindow();
3425 }
3426
3427 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003428 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003429 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3430
Vishnu Nair47074b82020-08-14 11:54:47 -07003431 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003432 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003433 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003434 mWindow->consumeFocusEvent(true);
3435 }
3436
Chris Ye2ad95392020-09-01 13:44:44 -07003437 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003438 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003439 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003440 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3441 mDispatcher->notifyKey(&keyArgs);
3442
3443 // Window should receive key down event.
3444 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3445 }
3446
3447 void expectKeyRepeatOnce(int32_t repeatCount) {
3448 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3449 InputEvent* repeatEvent = mWindow->consume();
3450 ASSERT_NE(nullptr, repeatEvent);
3451
3452 uint32_t eventType = repeatEvent->getType();
3453 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3454
3455 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3456 uint32_t eventAction = repeatKeyEvent->getAction();
3457 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3458 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3459 }
3460
Chris Ye2ad95392020-09-01 13:44:44 -07003461 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003462 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003463 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003464 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3465 mDispatcher->notifyKey(&keyArgs);
3466
3467 // Window should receive key down event.
3468 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3469 0 /*expectedFlags*/);
3470 }
3471};
3472
3473TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003474 sendAndConsumeKeyDown(1 /* deviceId */);
3475 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3476 expectKeyRepeatOnce(repeatCount);
3477 }
3478}
3479
3480TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3481 sendAndConsumeKeyDown(1 /* deviceId */);
3482 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3483 expectKeyRepeatOnce(repeatCount);
3484 }
3485 sendAndConsumeKeyDown(2 /* deviceId */);
3486 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003487 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3488 expectKeyRepeatOnce(repeatCount);
3489 }
3490}
3491
3492TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003493 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003494 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003495 sendAndConsumeKeyUp(1 /* deviceId */);
3496 mWindow->assertNoEvents();
3497}
3498
3499TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3500 sendAndConsumeKeyDown(1 /* deviceId */);
3501 expectKeyRepeatOnce(1 /*repeatCount*/);
3502 sendAndConsumeKeyDown(2 /* deviceId */);
3503 expectKeyRepeatOnce(1 /*repeatCount*/);
3504 // Stale key up from device 1.
3505 sendAndConsumeKeyUp(1 /* deviceId */);
3506 // Device 2 is still down, keep repeating
3507 expectKeyRepeatOnce(2 /*repeatCount*/);
3508 expectKeyRepeatOnce(3 /*repeatCount*/);
3509 // Device 2 key up
3510 sendAndConsumeKeyUp(2 /* deviceId */);
3511 mWindow->assertNoEvents();
3512}
3513
3514TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3515 sendAndConsumeKeyDown(1 /* deviceId */);
3516 expectKeyRepeatOnce(1 /*repeatCount*/);
3517 sendAndConsumeKeyDown(2 /* deviceId */);
3518 expectKeyRepeatOnce(1 /*repeatCount*/);
3519 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3520 sendAndConsumeKeyUp(2 /* deviceId */);
3521 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003522 mWindow->assertNoEvents();
3523}
3524
liushenxiang42232912021-05-21 20:24:09 +08003525TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3526 sendAndConsumeKeyDown(DEVICE_ID);
3527 expectKeyRepeatOnce(1 /*repeatCount*/);
3528 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3529 mDispatcher->notifyDeviceReset(&args);
3530 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3531 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3532 mWindow->assertNoEvents();
3533}
3534
Garfield Tan1c7bc862020-01-28 13:24:04 -08003535TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003536 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003537 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3538 InputEvent* repeatEvent = mWindow->consume();
3539 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3540 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3541 IdGenerator::getSource(repeatEvent->getId()));
3542 }
3543}
3544
3545TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003546 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003547
3548 std::unordered_set<int32_t> idSet;
3549 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3550 InputEvent* repeatEvent = mWindow->consume();
3551 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3552 int32_t id = repeatEvent->getId();
3553 EXPECT_EQ(idSet.end(), idSet.find(id));
3554 idSet.insert(id);
3555 }
3556}
3557
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003558/* Test InputDispatcher for MultiDisplay */
3559class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3560public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003561 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003562 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003563
Chris Yea209fde2020-07-22 13:54:51 -07003564 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003565 windowInPrimary =
3566 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003567
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003568 // Set focus window for primary display, but focused display would be second one.
3569 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003570 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003571 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003572 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003573 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003574
Chris Yea209fde2020-07-22 13:54:51 -07003575 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003576 windowInSecondary =
3577 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003578 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003579 // Set focus display to second one.
3580 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3581 // Set focus window for second display.
3582 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003583 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003584 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003585 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003586 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003587 }
3588
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003589 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003590 InputDispatcherTest::TearDown();
3591
Chris Yea209fde2020-07-22 13:54:51 -07003592 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003593 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003594 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003595 windowInSecondary.clear();
3596 }
3597
3598protected:
Chris Yea209fde2020-07-22 13:54:51 -07003599 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003600 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003601 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003602 sp<FakeWindowHandle> windowInSecondary;
3603};
3604
3605TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3606 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003607 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3608 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3609 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003610 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003611 windowInSecondary->assertNoEvents();
3612
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003613 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003614 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3615 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3616 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003617 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003618 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003619}
3620
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003621TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003622 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003623 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3624 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003625 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003626 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003627 windowInSecondary->assertNoEvents();
3628
3629 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003630 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003631 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003632 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003633 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003634
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003635 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003636 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003637
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003638 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003639 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3640 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003641
3642 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003643 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003644 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003645 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003646 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003647 windowInSecondary->assertNoEvents();
3648}
3649
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003650// Test per-display input monitors for motion event.
3651TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003652 FakeMonitorReceiver monitorInPrimary =
3653 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3654 FakeMonitorReceiver monitorInSecondary =
3655 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003656
3657 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003658 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3659 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3660 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003661 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003662 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003663 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003664 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003665
3666 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003667 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3668 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3669 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003670 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003671 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003672 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003673 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003674
3675 // Test inject a non-pointer motion event.
3676 // If specific a display, it will dispatch to the focused window of particular display,
3677 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003678 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3679 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3680 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003681 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003682 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003683 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003684 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003685}
3686
3687// Test per-display input monitors for key event.
3688TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003689 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003690 FakeMonitorReceiver monitorInPrimary =
3691 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3692 FakeMonitorReceiver monitorInSecondary =
3693 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003694
3695 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003696 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3697 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003698 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003699 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003700 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003701 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003702}
3703
Vishnu Nair958da932020-08-21 17:12:37 -07003704TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3705 sp<FakeWindowHandle> secondWindowInPrimary =
3706 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3707 secondWindowInPrimary->setFocusable(true);
3708 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3709 setFocusedWindow(secondWindowInPrimary);
3710 windowInPrimary->consumeFocusEvent(false);
3711 secondWindowInPrimary->consumeFocusEvent(true);
3712
3713 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003714 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3715 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003716 windowInPrimary->assertNoEvents();
3717 windowInSecondary->assertNoEvents();
3718 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3719}
3720
Arthur Hungdfd528e2021-12-08 13:23:04 +00003721TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3722 FakeMonitorReceiver monitorInPrimary =
3723 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3724 FakeMonitorReceiver monitorInSecondary =
3725 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3726
3727 // Test touch down on primary display.
3728 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3729 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3730 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3731 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3732 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3733
3734 // Test touch down on second display.
3735 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3736 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3737 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3738 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3739 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3740
3741 // Trigger cancel touch.
3742 mDispatcher->cancelCurrentTouch();
3743 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3744 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3745 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3746 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3747
3748 // Test inject a move motion event, no window/monitor should receive the event.
3749 ASSERT_EQ(InputEventInjectionResult::FAILED,
3750 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3751 ADISPLAY_ID_DEFAULT, {110, 200}))
3752 << "Inject motion event should return InputEventInjectionResult::FAILED";
3753 windowInPrimary->assertNoEvents();
3754 monitorInPrimary.assertNoEvents();
3755
3756 ASSERT_EQ(InputEventInjectionResult::FAILED,
3757 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3758 SECOND_DISPLAY_ID, {110, 200}))
3759 << "Inject motion event should return InputEventInjectionResult::FAILED";
3760 windowInSecondary->assertNoEvents();
3761 monitorInSecondary.assertNoEvents();
3762}
3763
Jackal Guof9696682018-10-05 12:23:23 +08003764class InputFilterTest : public InputDispatcherTest {
3765protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003766 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3767 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003768 NotifyMotionArgs motionArgs;
3769
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003770 motionArgs =
3771 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003772 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003773 motionArgs =
3774 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003775 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003776 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003777 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003778 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3779 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003780 } else {
3781 mFakePolicy->assertFilterInputEventWasNotCalled();
3782 }
3783 }
3784
3785 void testNotifyKey(bool expectToBeFiltered) {
3786 NotifyKeyArgs keyArgs;
3787
3788 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3789 mDispatcher->notifyKey(&keyArgs);
3790 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3791 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003792 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003793
3794 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003795 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003796 } else {
3797 mFakePolicy->assertFilterInputEventWasNotCalled();
3798 }
3799 }
3800};
3801
3802// Test InputFilter for MotionEvent
3803TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3804 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3805 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3806 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3807
3808 // Enable InputFilter
3809 mDispatcher->setInputFilterEnabled(true);
3810 // Test touch on both primary and second display, and check if both events are filtered.
3811 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3812 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3813
3814 // Disable InputFilter
3815 mDispatcher->setInputFilterEnabled(false);
3816 // Test touch on both primary and second display, and check if both events aren't filtered.
3817 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3818 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3819}
3820
3821// Test InputFilter for KeyEvent
3822TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3823 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3824 testNotifyKey(/*expectToBeFiltered*/ false);
3825
3826 // Enable InputFilter
3827 mDispatcher->setInputFilterEnabled(true);
3828 // Send a key event, and check if it is filtered.
3829 testNotifyKey(/*expectToBeFiltered*/ true);
3830
3831 // Disable InputFilter
3832 mDispatcher->setInputFilterEnabled(false);
3833 // Send a key event, and check if it isn't filtered.
3834 testNotifyKey(/*expectToBeFiltered*/ false);
3835}
3836
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003837// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3838// logical display coordinate space.
3839TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3840 ui::Transform firstDisplayTransform;
3841 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3842 ui::Transform secondDisplayTransform;
3843 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3844
3845 std::vector<gui::DisplayInfo> displayInfos(2);
3846 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3847 displayInfos[0].transform = firstDisplayTransform;
3848 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3849 displayInfos[1].transform = secondDisplayTransform;
3850
3851 mDispatcher->onWindowInfosChanged({}, displayInfos);
3852
3853 // Enable InputFilter
3854 mDispatcher->setInputFilterEnabled(true);
3855
3856 // Ensure the correct transforms are used for the displays.
3857 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3858 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3859}
3860
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003861class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3862protected:
3863 virtual void SetUp() override {
3864 InputDispatcherTest::SetUp();
3865
3866 /**
3867 * We don't need to enable input filter to test the injected event policy, but we enabled it
3868 * here to make the tests more realistic, since this policy only matters when inputfilter is
3869 * on.
3870 */
3871 mDispatcher->setInputFilterEnabled(true);
3872
3873 std::shared_ptr<InputApplicationHandle> application =
3874 std::make_shared<FakeApplicationHandle>();
3875 mWindow =
3876 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3877
3878 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3879 mWindow->setFocusable(true);
3880 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3881 setFocusedWindow(mWindow);
3882 mWindow->consumeFocusEvent(true);
3883 }
3884
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003885 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3886 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003887 KeyEvent event;
3888
3889 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3890 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3891 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3892 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3893 const int32_t additionalPolicyFlags =
3894 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3895 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3896 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3897 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3898 policyFlags | additionalPolicyFlags));
3899
3900 InputEvent* received = mWindow->consume();
3901 ASSERT_NE(nullptr, received);
3902 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003903 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3904 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3905 ASSERT_EQ(flags, keyEvent.getFlags());
3906 }
3907
3908 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3909 int32_t flags) {
3910 MotionEvent event;
3911 PointerProperties pointerProperties[1];
3912 PointerCoords pointerCoords[1];
3913 pointerProperties[0].clear();
3914 pointerProperties[0].id = 0;
3915 pointerCoords[0].clear();
3916 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3917 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3918
3919 ui::Transform identityTransform;
3920 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3921 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3922 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3923 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3924 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003925 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003926 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003927 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3928
3929 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3930 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3931 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3932 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3933 policyFlags | additionalPolicyFlags));
3934
3935 InputEvent* received = mWindow->consume();
3936 ASSERT_NE(nullptr, received);
3937 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3938 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3939 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3940 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003941 }
3942
3943private:
3944 sp<FakeWindowHandle> mWindow;
3945};
3946
3947TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003948 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3949 // filter. Without it, the event will no different from a regularly injected event, and the
3950 // injected device id will be overwritten.
3951 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3952 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003953}
3954
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003955TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003956 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003957 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3958 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3959}
3960
3961TEST_F(InputFilterInjectionPolicyTest,
3962 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3963 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3964 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3965 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003966}
3967
3968TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3969 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003970 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003971}
3972
chaviwfd6d3512019-03-25 13:23:49 -07003973class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003974 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003975 InputDispatcherTest::SetUp();
3976
Chris Yea209fde2020-07-22 13:54:51 -07003977 std::shared_ptr<FakeApplicationHandle> application =
3978 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003979 mUnfocusedWindow =
3980 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003981 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3982 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3983 // window.
chaviw3277faf2021-05-19 16:45:23 -05003984 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003985
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003986 mFocusedWindow =
3987 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3988 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05003989 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003990
3991 // Set focused application.
3992 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003993 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003994
3995 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003996 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003997 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003998 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003999 }
4000
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004001 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004002 InputDispatcherTest::TearDown();
4003
4004 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004005 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004006 }
4007
4008protected:
4009 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004010 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004011 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004012};
4013
4014// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4015// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4016// the onPointerDownOutsideFocus callback.
4017TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004018 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004019 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4020 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004021 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004022 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004023
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004024 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004025 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4026}
4027
4028// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4029// DOWN on the window that doesn't have focus. Ensure no window received the
4030// onPointerDownOutsideFocus callback.
4031TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004032 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004033 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004034 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004035 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004036
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004037 ASSERT_TRUE(mDispatcher->waitForIdle());
4038 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004039}
4040
4041// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4042// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4043TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004044 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4045 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004046 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004047 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004048
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004049 ASSERT_TRUE(mDispatcher->waitForIdle());
4050 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004051}
4052
4053// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4054// DOWN on the window that already has focus. Ensure no window received the
4055// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004056TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004057 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004058 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004059 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004060 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004061 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004062
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004063 ASSERT_TRUE(mDispatcher->waitForIdle());
4064 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004065}
4066
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004067// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4068// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4069TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4070 const MotionEvent event =
4071 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4072 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4073 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4074 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4075 .build();
4076 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4077 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4078 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4079
4080 ASSERT_TRUE(mDispatcher->waitForIdle());
4081 mFakePolicy->assertOnPointerDownWasNotCalled();
4082 // Ensure that the unfocused window did not receive any FOCUS events.
4083 mUnfocusedWindow->assertNoEvents();
4084}
4085
chaviwaf87b3e2019-10-01 16:59:28 -07004086// These tests ensures we can send touch events to a single client when there are multiple input
4087// windows that point to the same client token.
4088class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4089 virtual void SetUp() override {
4090 InputDispatcherTest::SetUp();
4091
Chris Yea209fde2020-07-22 13:54:51 -07004092 std::shared_ptr<FakeApplicationHandle> application =
4093 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004094 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4095 ADISPLAY_ID_DEFAULT);
4096 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
4097 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05004098 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004099 mWindow1->setFrame(Rect(0, 0, 100, 100));
4100
4101 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4102 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05004103 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004104 mWindow2->setFrame(Rect(100, 100, 200, 200));
4105
Arthur Hung72d8dc32020-03-28 00:48:39 +00004106 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004107 }
4108
4109protected:
4110 sp<FakeWindowHandle> mWindow1;
4111 sp<FakeWindowHandle> mWindow2;
4112
4113 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004114 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004115 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4116 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004117 }
4118
4119 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4120 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004121 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004122 InputEvent* event = window->consume();
4123
4124 ASSERT_NE(nullptr, event) << name.c_str()
4125 << ": consumer should have returned non-NULL event.";
4126
4127 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4128 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4129 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4130
4131 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004132 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004133
4134 for (size_t i = 0; i < points.size(); i++) {
4135 float expectedX = points[i].x;
4136 float expectedY = points[i].y;
4137
4138 EXPECT_EQ(expectedX, motionEvent.getX(i))
4139 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4140 << ", got " << motionEvent.getX(i);
4141 EXPECT_EQ(expectedY, motionEvent.getY(i))
4142 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4143 << ", got " << motionEvent.getY(i);
4144 }
4145 }
chaviw9eaa22c2020-07-01 16:21:27 -07004146
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004147 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004148 std::vector<PointF> expectedPoints) {
4149 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4150 ADISPLAY_ID_DEFAULT, touchedPoints);
4151 mDispatcher->notifyMotion(&motionArgs);
4152
4153 // Always consume from window1 since it's the window that has the InputReceiver
4154 consumeMotionEvent(mWindow1, action, expectedPoints);
4155 }
chaviwaf87b3e2019-10-01 16:59:28 -07004156};
4157
4158TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4159 // Touch Window 1
4160 PointF touchedPoint = {10, 10};
4161 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004162 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004163
4164 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004165 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004166
4167 // Touch Window 2
4168 touchedPoint = {150, 150};
4169 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004170 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004171}
4172
chaviw9eaa22c2020-07-01 16:21:27 -07004173TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4174 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004175 mWindow2->setWindowScale(0.5f, 0.5f);
4176
4177 // Touch Window 1
4178 PointF touchedPoint = {10, 10};
4179 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004180 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004181 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004182 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004183
4184 // Touch Window 2
4185 touchedPoint = {150, 150};
4186 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004187 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4188 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004189
chaviw9eaa22c2020-07-01 16:21:27 -07004190 // Update the transform so rotation is set
4191 mWindow2->setWindowTransform(0, -1, 1, 0);
4192 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4193 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004194}
4195
chaviw9eaa22c2020-07-01 16:21:27 -07004196TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004197 mWindow2->setWindowScale(0.5f, 0.5f);
4198
4199 // Touch Window 1
4200 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4201 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004202 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004203
4204 // Touch Window 2
4205 int32_t actionPointerDown =
4206 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004207 touchedPoints.push_back(PointF{150, 150});
4208 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4209 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004210
chaviw9eaa22c2020-07-01 16:21:27 -07004211 // Release Window 2
4212 int32_t actionPointerUp =
4213 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4214 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4215 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004216
chaviw9eaa22c2020-07-01 16:21:27 -07004217 // Update the transform so rotation is set for Window 2
4218 mWindow2->setWindowTransform(0, -1, 1, 0);
4219 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4220 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004221}
4222
chaviw9eaa22c2020-07-01 16:21:27 -07004223TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004224 mWindow2->setWindowScale(0.5f, 0.5f);
4225
4226 // Touch Window 1
4227 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4228 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004229 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004230
4231 // Touch Window 2
4232 int32_t actionPointerDown =
4233 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004234 touchedPoints.push_back(PointF{150, 150});
4235 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004236
chaviw9eaa22c2020-07-01 16:21:27 -07004237 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004238
4239 // Move both windows
4240 touchedPoints = {{20, 20}, {175, 175}};
4241 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4242 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4243
chaviw9eaa22c2020-07-01 16:21:27 -07004244 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004245
chaviw9eaa22c2020-07-01 16:21:27 -07004246 // Release Window 2
4247 int32_t actionPointerUp =
4248 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4249 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4250 expectedPoints.pop_back();
4251
4252 // Touch Window 2
4253 mWindow2->setWindowTransform(0, -1, 1, 0);
4254 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4255 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4256
4257 // Move both windows
4258 touchedPoints = {{20, 20}, {175, 175}};
4259 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4260 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4261
4262 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004263}
4264
4265TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4266 mWindow1->setWindowScale(0.5f, 0.5f);
4267
4268 // Touch Window 1
4269 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4270 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004271 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004272
4273 // Touch Window 2
4274 int32_t actionPointerDown =
4275 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004276 touchedPoints.push_back(PointF{150, 150});
4277 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004278
chaviw9eaa22c2020-07-01 16:21:27 -07004279 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004280
4281 // Move both windows
4282 touchedPoints = {{20, 20}, {175, 175}};
4283 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4284 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4285
chaviw9eaa22c2020-07-01 16:21:27 -07004286 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004287}
4288
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004289class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4290 virtual void SetUp() override {
4291 InputDispatcherTest::SetUp();
4292
Chris Yea209fde2020-07-22 13:54:51 -07004293 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004294 mApplication->setDispatchingTimeout(20ms);
4295 mWindow =
4296 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4297 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004298 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004299 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004300 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4301 // window.
chaviw3277faf2021-05-19 16:45:23 -05004302 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004303
4304 // Set focused application.
4305 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4306
4307 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004308 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004309 mWindow->consumeFocusEvent(true);
4310 }
4311
4312 virtual void TearDown() override {
4313 InputDispatcherTest::TearDown();
4314 mWindow.clear();
4315 }
4316
4317protected:
Chris Yea209fde2020-07-22 13:54:51 -07004318 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004319 sp<FakeWindowHandle> mWindow;
4320 static constexpr PointF WINDOW_LOCATION = {20, 20};
4321
4322 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004323 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004324 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4325 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004326 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004327 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4328 WINDOW_LOCATION));
4329 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004330
4331 sp<FakeWindowHandle> addSpyWindow() {
4332 sp<FakeWindowHandle> spy =
4333 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4334 spy->setTrustedOverlay(true);
4335 spy->setFocusable(false);
4336 spy->setInputFeatures(WindowInfo::Feature::SPY);
4337 spy->setDispatchingTimeout(30ms);
4338 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4339 return spy;
4340 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004341};
4342
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004343// Send a tap and respond, which should not cause an ANR.
4344TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4345 tapOnWindow();
4346 mWindow->consumeMotionDown();
4347 mWindow->consumeMotionUp();
4348 ASSERT_TRUE(mDispatcher->waitForIdle());
4349 mFakePolicy->assertNotifyAnrWasNotCalled();
4350}
4351
4352// Send a regular key and respond, which should not cause an ANR.
4353TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004354 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004355 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4356 ASSERT_TRUE(mDispatcher->waitForIdle());
4357 mFakePolicy->assertNotifyAnrWasNotCalled();
4358}
4359
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004360TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4361 mWindow->setFocusable(false);
4362 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4363 mWindow->consumeFocusEvent(false);
4364
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004365 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004366 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004367 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4368 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004369 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004370 // Key will not go to window because we have no focused window.
4371 // The 'no focused window' ANR timer should start instead.
4372
4373 // Now, the focused application goes away.
4374 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4375 // The key should get dropped and there should be no ANR.
4376
4377 ASSERT_TRUE(mDispatcher->waitForIdle());
4378 mFakePolicy->assertNotifyAnrWasNotCalled();
4379}
4380
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004381// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004382// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4383// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004384TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004385 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004386 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4387 WINDOW_LOCATION));
4388
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004389 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4390 ASSERT_TRUE(sequenceNum);
4391 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004392 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004393
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004394 mWindow->finishEvent(*sequenceNum);
4395 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4396 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004397 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004398 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004399}
4400
4401// Send a key to the app and have the app not respond right away.
4402TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4403 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004404 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004405 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4406 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004407 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004408 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004409 ASSERT_TRUE(mDispatcher->waitForIdle());
4410}
4411
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004412// We have a focused application, but no focused window
4413TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004414 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004415 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4416 mWindow->consumeFocusEvent(false);
4417
4418 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004419 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004420 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4421 WINDOW_LOCATION));
4422 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4423 mDispatcher->waitForIdle();
4424 mFakePolicy->assertNotifyAnrWasNotCalled();
4425
4426 // Once a focused event arrives, we get an ANR for this application
4427 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4428 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004429 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004430 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004431 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004432 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004433 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004434 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004435 ASSERT_TRUE(mDispatcher->waitForIdle());
4436}
4437
4438// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004439// Make sure that we don't notify policy twice about the same ANR.
4440TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004441 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004442 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4443 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004444
4445 // Once a focused event arrives, we get an ANR for this application
4446 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4447 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004448 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004449 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004450 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004451 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004452 const std::chrono::duration appTimeout =
4453 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004454 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004455
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004456 std::this_thread::sleep_for(appTimeout);
4457 // ANR should not be raised again. It is up to policy to do that if it desires.
4458 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004459
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004460 // If we now get a focused window, the ANR should stop, but the policy handles that via
4461 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004462 ASSERT_TRUE(mDispatcher->waitForIdle());
4463}
4464
4465// We have a focused application, but no focused window
4466TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004467 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004468 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4469 mWindow->consumeFocusEvent(false);
4470
4471 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004472 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004473 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004474 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4475 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004476
4477 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004478 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004479
4480 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004481 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004482 ASSERT_TRUE(mDispatcher->waitForIdle());
4483 mWindow->assertNoEvents();
4484}
4485
4486/**
4487 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4488 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4489 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4490 * the ANR mechanism should still work.
4491 *
4492 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4493 * DOWN event, while not responding on the second one.
4494 */
4495TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4496 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4497 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4498 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4499 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4500 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004501 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004502
4503 // Now send ACTION_UP, with identical timestamp
4504 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4505 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4506 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4507 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004508 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004509
4510 // We have now sent down and up. Let's consume first event and then ANR on the second.
4511 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4512 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004513 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004514}
4515
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004516// A spy window can receive an ANR
4517TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4518 sp<FakeWindowHandle> spy = addSpyWindow();
4519
4520 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4521 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4522 WINDOW_LOCATION));
4523 mWindow->consumeMotionDown();
4524
4525 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4526 ASSERT_TRUE(sequenceNum);
4527 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4528 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy->getToken());
4529
4530 spy->finishEvent(*sequenceNum);
4531 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4532 0 /*flags*/);
4533 ASSERT_TRUE(mDispatcher->waitForIdle());
4534 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken());
4535}
4536
4537// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004538// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004539TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4540 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004541
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004542 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4543 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004544 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004545 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004546
4547 // Stuck on the ACTION_UP
4548 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004549 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004550
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004551 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004552 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004553 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4554 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004555
4556 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4557 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004558 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004559 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004560 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004561}
4562
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004563// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004564// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004565TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4566 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004567
4568 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004569 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4570 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004571
4572 mWindow->consumeMotionDown();
4573 // Stuck on the ACTION_UP
4574 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004575 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004576
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004577 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004578 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004579 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4580 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004581
4582 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4583 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004584 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004585 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004586 spy->assertNoEvents();
4587}
4588
4589TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4590 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4591
4592 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4593
4594 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4595 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4596 WINDOW_LOCATION));
4597
4598 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4599 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4600 ASSERT_TRUE(consumeSeq);
4601
4602 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(30ms);
4603
4604 monitor.finishEvent(*consumeSeq);
4605 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4606
4607 ASSERT_TRUE(mDispatcher->waitForIdle());
4608 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004609}
4610
4611// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4612// process events, you don't get an anr. When the window later becomes unresponsive again, you
4613// get an ANR again.
4614// 1. tap -> block on ACTION_UP -> receive ANR
4615// 2. consume all pending events (= queue becomes healthy again)
4616// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4617TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4618 tapOnWindow();
4619
4620 mWindow->consumeMotionDown();
4621 // Block on ACTION_UP
4622 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004623 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004624 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4625 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004626 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004627 mWindow->assertNoEvents();
4628
4629 tapOnWindow();
4630 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004631 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004632 mWindow->consumeMotionUp();
4633
4634 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004635 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004636 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004637 mWindow->assertNoEvents();
4638}
4639
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004640// If a connection remains unresponsive for a while, make sure policy is only notified once about
4641// it.
4642TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004643 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004644 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4645 WINDOW_LOCATION));
4646
4647 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004648 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004649 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004650 // 'notifyConnectionUnresponsive' should only be called once per connection
4651 mFakePolicy->assertNotifyAnrWasNotCalled();
4652 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004653 mWindow->consumeMotionDown();
4654 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4655 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4656 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004657 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004658 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004659 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004660}
4661
4662/**
4663 * If a window is processing a motion event, and then a key event comes in, the key event should
4664 * not to to the focused window until the motion is processed.
4665 *
4666 * Warning!!!
4667 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4668 * and the injection timeout that we specify when injecting the key.
4669 * We must have the injection timeout (10ms) be smaller than
4670 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4671 *
4672 * If that value changes, this test should also change.
4673 */
4674TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4675 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4676 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4677
4678 tapOnWindow();
4679 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4680 ASSERT_TRUE(downSequenceNum);
4681 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4682 ASSERT_TRUE(upSequenceNum);
4683 // Don't finish the events yet, and send a key
4684 // Injection will "succeed" because we will eventually give up and send the key to the focused
4685 // window even if motions are still being processed. But because the injection timeout is short,
4686 // we will receive INJECTION_TIMED_OUT as the result.
4687
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004688 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004689 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004690 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4691 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004692 // Key will not be sent to the window, yet, because the window is still processing events
4693 // and the key remains pending, waiting for the touch events to be processed
4694 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4695 ASSERT_FALSE(keySequenceNum);
4696
4697 std::this_thread::sleep_for(500ms);
4698 // if we wait long enough though, dispatcher will give up, and still send the key
4699 // to the focused window, even though we have not yet finished the motion event
4700 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4701 mWindow->finishEvent(*downSequenceNum);
4702 mWindow->finishEvent(*upSequenceNum);
4703}
4704
4705/**
4706 * If a window is processing a motion event, and then a key event comes in, the key event should
4707 * not go to the focused window until the motion is processed.
4708 * If then a new motion comes in, then the pending key event should be going to the currently
4709 * focused window right away.
4710 */
4711TEST_F(InputDispatcherSingleWindowAnr,
4712 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4713 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4714 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4715
4716 tapOnWindow();
4717 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4718 ASSERT_TRUE(downSequenceNum);
4719 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4720 ASSERT_TRUE(upSequenceNum);
4721 // Don't finish the events yet, and send a key
4722 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004723 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004724 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004725 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004726 // At this point, key is still pending, and should not be sent to the application yet.
4727 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4728 ASSERT_FALSE(keySequenceNum);
4729
4730 // Now tap down again. It should cause the pending key to go to the focused window right away.
4731 tapOnWindow();
4732 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4733 // the other events yet. We can finish events in any order.
4734 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4735 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4736 mWindow->consumeMotionDown();
4737 mWindow->consumeMotionUp();
4738 mWindow->assertNoEvents();
4739}
4740
4741class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4742 virtual void SetUp() override {
4743 InputDispatcherTest::SetUp();
4744
Chris Yea209fde2020-07-22 13:54:51 -07004745 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004746 mApplication->setDispatchingTimeout(10ms);
4747 mUnfocusedWindow =
4748 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4749 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4750 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4751 // window.
4752 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004753 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4754 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4755 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004756
4757 mFocusedWindow =
4758 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004759 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004760 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004761 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004762
4763 // Set focused application.
4764 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004765 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004766
4767 // Expect one focus window exist in display.
4768 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004769 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004770 mFocusedWindow->consumeFocusEvent(true);
4771 }
4772
4773 virtual void TearDown() override {
4774 InputDispatcherTest::TearDown();
4775
4776 mUnfocusedWindow.clear();
4777 mFocusedWindow.clear();
4778 }
4779
4780protected:
Chris Yea209fde2020-07-22 13:54:51 -07004781 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004782 sp<FakeWindowHandle> mUnfocusedWindow;
4783 sp<FakeWindowHandle> mFocusedWindow;
4784 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4785 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4786 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4787
4788 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4789
4790 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4791
4792private:
4793 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004794 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004795 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4796 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004797 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004798 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4799 location));
4800 }
4801};
4802
4803// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4804// should be ANR'd first.
4805TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004806 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004807 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4808 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004809 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004810 mFocusedWindow->consumeMotionDown();
4811 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4812 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4813 // We consumed all events, so no ANR
4814 ASSERT_TRUE(mDispatcher->waitForIdle());
4815 mFakePolicy->assertNotifyAnrWasNotCalled();
4816
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004817 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004818 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4819 FOCUSED_WINDOW_LOCATION));
4820 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4821 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004822
4823 const std::chrono::duration timeout =
4824 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004825 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004826 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4827 // sequence to make it consistent
4828 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004829 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004830 mFocusedWindow->consumeMotionDown();
4831 // This cancel is generated because the connection was unresponsive
4832 mFocusedWindow->consumeMotionCancel();
4833 mFocusedWindow->assertNoEvents();
4834 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004835 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004836 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004837 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004838}
4839
4840// If we have 2 windows with identical timeouts that are both unresponsive,
4841// it doesn't matter which order they should have ANR.
4842// But we should receive ANR for both.
4843TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4844 // Set the timeout for unfocused window to match the focused window
4845 mUnfocusedWindow->setDispatchingTimeout(10ms);
4846 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4847
4848 tapOnFocusedWindow();
4849 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004850 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4851 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004852
4853 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004854 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4855 mFocusedWindow->getToken() == anrConnectionToken2);
4856 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4857 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004858
4859 ASSERT_TRUE(mDispatcher->waitForIdle());
4860 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004861
4862 mFocusedWindow->consumeMotionDown();
4863 mFocusedWindow->consumeMotionUp();
4864 mUnfocusedWindow->consumeMotionOutside();
4865
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004866 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4867 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004868
4869 // Both applications should be marked as responsive, in any order
4870 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4871 mFocusedWindow->getToken() == responsiveToken2);
4872 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4873 mUnfocusedWindow->getToken() == responsiveToken2);
4874 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004875}
4876
4877// If a window is already not responding, the second tap on the same window should be ignored.
4878// We should also log an error to account for the dropped event (not tested here).
4879// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4880TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4881 tapOnFocusedWindow();
4882 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4883 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4884 // Receive the events, but don't respond
4885 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4886 ASSERT_TRUE(downEventSequenceNum);
4887 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4888 ASSERT_TRUE(upEventSequenceNum);
4889 const std::chrono::duration timeout =
4890 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004891 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004892
4893 // Tap once again
4894 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004895 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004896 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4897 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004898 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004899 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4900 FOCUSED_WINDOW_LOCATION));
4901 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4902 // valid touch target
4903 mUnfocusedWindow->assertNoEvents();
4904
4905 // Consume the first tap
4906 mFocusedWindow->finishEvent(*downEventSequenceNum);
4907 mFocusedWindow->finishEvent(*upEventSequenceNum);
4908 ASSERT_TRUE(mDispatcher->waitForIdle());
4909 // The second tap did not go to the focused window
4910 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004911 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004912 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004913 mFakePolicy->assertNotifyAnrWasNotCalled();
4914}
4915
4916// If you tap outside of all windows, there will not be ANR
4917TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004918 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004919 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4920 LOCATION_OUTSIDE_ALL_WINDOWS));
4921 ASSERT_TRUE(mDispatcher->waitForIdle());
4922 mFakePolicy->assertNotifyAnrWasNotCalled();
4923}
4924
4925// Since the focused window is paused, tapping on it should not produce any events
4926TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4927 mFocusedWindow->setPaused(true);
4928 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4929
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004930 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004931 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4932 FOCUSED_WINDOW_LOCATION));
4933
4934 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4935 ASSERT_TRUE(mDispatcher->waitForIdle());
4936 // Should not ANR because the window is paused, and touches shouldn't go to it
4937 mFakePolicy->assertNotifyAnrWasNotCalled();
4938
4939 mFocusedWindow->assertNoEvents();
4940 mUnfocusedWindow->assertNoEvents();
4941}
4942
4943/**
4944 * If a window is processing a motion event, and then a key event comes in, the key event should
4945 * not to to the focused window until the motion is processed.
4946 * If a different window becomes focused at this time, the key should go to that window instead.
4947 *
4948 * Warning!!!
4949 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4950 * and the injection timeout that we specify when injecting the key.
4951 * We must have the injection timeout (10ms) be smaller than
4952 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4953 *
4954 * If that value changes, this test should also change.
4955 */
4956TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4957 // Set a long ANR timeout to prevent it from triggering
4958 mFocusedWindow->setDispatchingTimeout(2s);
4959 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4960
4961 tapOnUnfocusedWindow();
4962 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4963 ASSERT_TRUE(downSequenceNum);
4964 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4965 ASSERT_TRUE(upSequenceNum);
4966 // Don't finish the events yet, and send a key
4967 // Injection will succeed because we will eventually give up and send the key to the focused
4968 // window even if motions are still being processed.
4969
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004970 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004971 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004972 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4973 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004974 // Key will not be sent to the window, yet, because the window is still processing events
4975 // and the key remains pending, waiting for the touch events to be processed
4976 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4977 ASSERT_FALSE(keySequenceNum);
4978
4979 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004980 mFocusedWindow->setFocusable(false);
4981 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004982 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004983 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004984
4985 // Focus events should precede the key events
4986 mUnfocusedWindow->consumeFocusEvent(true);
4987 mFocusedWindow->consumeFocusEvent(false);
4988
4989 // Finish the tap events, which should unblock dispatcher
4990 mUnfocusedWindow->finishEvent(*downSequenceNum);
4991 mUnfocusedWindow->finishEvent(*upSequenceNum);
4992
4993 // Now that all queues are cleared and no backlog in the connections, the key event
4994 // can finally go to the newly focused "mUnfocusedWindow".
4995 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4996 mFocusedWindow->assertNoEvents();
4997 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004998 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004999}
5000
5001// When the touch stream is split across 2 windows, and one of them does not respond,
5002// then ANR should be raised and the touch should be canceled for the unresponsive window.
5003// The other window should not be affected by that.
5004TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5005 // Touch Window 1
5006 NotifyMotionArgs motionArgs =
5007 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5008 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5009 mDispatcher->notifyMotion(&motionArgs);
5010 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5011 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5012
5013 // Touch Window 2
5014 int32_t actionPointerDown =
5015 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
5016
5017 motionArgs =
5018 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5019 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
5020 mDispatcher->notifyMotion(&motionArgs);
5021
5022 const std::chrono::duration timeout =
5023 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005024 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005025
5026 mUnfocusedWindow->consumeMotionDown();
5027 mFocusedWindow->consumeMotionDown();
5028 // Focused window may or may not receive ACTION_MOVE
5029 // But it should definitely receive ACTION_CANCEL due to the ANR
5030 InputEvent* event;
5031 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5032 ASSERT_TRUE(moveOrCancelSequenceNum);
5033 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5034 ASSERT_NE(nullptr, event);
5035 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5036 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5037 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5038 mFocusedWindow->consumeMotionCancel();
5039 } else {
5040 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5041 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005042 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005043 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005044
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005045 mUnfocusedWindow->assertNoEvents();
5046 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005047 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005048}
5049
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005050/**
5051 * If we have no focused window, and a key comes in, we start the ANR timer.
5052 * The focused application should add a focused window before the timer runs out to prevent ANR.
5053 *
5054 * If the user touches another application during this time, the key should be dropped.
5055 * Next, if a new focused window comes in, without toggling the focused application,
5056 * then no ANR should occur.
5057 *
5058 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5059 * but in some cases the policy may not update the focused application.
5060 */
5061TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5062 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5063 std::make_shared<FakeApplicationHandle>();
5064 focusedApplication->setDispatchingTimeout(60ms);
5065 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5066 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5067 mFocusedWindow->setFocusable(false);
5068
5069 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5070 mFocusedWindow->consumeFocusEvent(false);
5071
5072 // Send a key. The ANR timer should start because there is no focused window.
5073 // 'focusedApplication' will get blamed if this timer completes.
5074 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005075 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005076 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005077 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5078 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005079 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005080
5081 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5082 // then the injected touches won't cause the focused event to get dropped.
5083 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5084 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5085 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5086 // For this test, it means that the key would get delivered to the window once it becomes
5087 // focused.
5088 std::this_thread::sleep_for(10ms);
5089
5090 // Touch unfocused window. This should force the pending key to get dropped.
5091 NotifyMotionArgs motionArgs =
5092 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5093 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5094 mDispatcher->notifyMotion(&motionArgs);
5095
5096 // We do not consume the motion right away, because that would require dispatcher to first
5097 // process (== drop) the key event, and by that time, ANR will be raised.
5098 // Set the focused window first.
5099 mFocusedWindow->setFocusable(true);
5100 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5101 setFocusedWindow(mFocusedWindow);
5102 mFocusedWindow->consumeFocusEvent(true);
5103 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5104 // to another application. This could be a bug / behaviour in the policy.
5105
5106 mUnfocusedWindow->consumeMotionDown();
5107
5108 ASSERT_TRUE(mDispatcher->waitForIdle());
5109 // Should not ANR because we actually have a focused window. It was just added too slowly.
5110 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5111}
5112
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005113// These tests ensure we cannot send touch events to a window that's positioned behind a window
5114// that has feature NO_INPUT_CHANNEL.
5115// Layout:
5116// Top (closest to user)
5117// mNoInputWindow (above all windows)
5118// mBottomWindow
5119// Bottom (furthest from user)
5120class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5121 virtual void SetUp() override {
5122 InputDispatcherTest::SetUp();
5123
5124 mApplication = std::make_shared<FakeApplicationHandle>();
5125 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5126 "Window without input channel", ADISPLAY_ID_DEFAULT,
5127 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5128
chaviw3277faf2021-05-19 16:45:23 -05005129 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005130 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5131 // It's perfectly valid for this window to not have an associated input channel
5132
5133 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5134 ADISPLAY_ID_DEFAULT);
5135 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5136
5137 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5138 }
5139
5140protected:
5141 std::shared_ptr<FakeApplicationHandle> mApplication;
5142 sp<FakeWindowHandle> mNoInputWindow;
5143 sp<FakeWindowHandle> mBottomWindow;
5144};
5145
5146TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5147 PointF touchedPoint = {10, 10};
5148
5149 NotifyMotionArgs motionArgs =
5150 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5151 ADISPLAY_ID_DEFAULT, {touchedPoint});
5152 mDispatcher->notifyMotion(&motionArgs);
5153
5154 mNoInputWindow->assertNoEvents();
5155 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5156 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5157 // and therefore should prevent mBottomWindow from receiving touches
5158 mBottomWindow->assertNoEvents();
5159}
5160
5161/**
5162 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5163 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5164 */
5165TEST_F(InputDispatcherMultiWindowOcclusionTests,
5166 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5167 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5168 "Window with input channel and NO_INPUT_CHANNEL",
5169 ADISPLAY_ID_DEFAULT);
5170
chaviw3277faf2021-05-19 16:45:23 -05005171 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005172 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5173 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5174
5175 PointF touchedPoint = {10, 10};
5176
5177 NotifyMotionArgs motionArgs =
5178 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5179 ADISPLAY_ID_DEFAULT, {touchedPoint});
5180 mDispatcher->notifyMotion(&motionArgs);
5181
5182 mNoInputWindow->assertNoEvents();
5183 mBottomWindow->assertNoEvents();
5184}
5185
Vishnu Nair958da932020-08-21 17:12:37 -07005186class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5187protected:
5188 std::shared_ptr<FakeApplicationHandle> mApp;
5189 sp<FakeWindowHandle> mWindow;
5190 sp<FakeWindowHandle> mMirror;
5191
5192 virtual void SetUp() override {
5193 InputDispatcherTest::SetUp();
5194 mApp = std::make_shared<FakeApplicationHandle>();
5195 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5196 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5197 mWindow->getToken());
5198 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5199 mWindow->setFocusable(true);
5200 mMirror->setFocusable(true);
5201 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5202 }
5203};
5204
5205TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5206 // Request focus on a mirrored window
5207 setFocusedWindow(mMirror);
5208
5209 // window gets focused
5210 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005211 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5212 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005213 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5214}
5215
5216// A focused & mirrored window remains focused only if the window and its mirror are both
5217// focusable.
5218TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5219 setFocusedWindow(mMirror);
5220
5221 // window gets focused
5222 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005223 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5224 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005225 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005226 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5227 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005228 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5229
5230 mMirror->setFocusable(false);
5231 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5232
5233 // window loses focus since one of the windows associated with the token in not focusable
5234 mWindow->consumeFocusEvent(false);
5235
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005236 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5237 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005238 mWindow->assertNoEvents();
5239}
5240
5241// A focused & mirrored window remains focused until the window and its mirror both become
5242// invisible.
5243TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5244 setFocusedWindow(mMirror);
5245
5246 // window gets focused
5247 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005248 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5249 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005250 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005251 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5252 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005253 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5254
5255 mMirror->setVisible(false);
5256 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5257
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005258 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5259 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005260 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005261 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5262 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005263 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5264
5265 mWindow->setVisible(false);
5266 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5267
5268 // window loses focus only after all windows associated with the token become invisible.
5269 mWindow->consumeFocusEvent(false);
5270
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005271 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5272 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005273 mWindow->assertNoEvents();
5274}
5275
5276// A focused & mirrored window remains focused until both windows are removed.
5277TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5278 setFocusedWindow(mMirror);
5279
5280 // window gets focused
5281 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005282 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5283 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005284 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005285 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5286 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005287 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5288
5289 // single window is removed but the window token remains focused
5290 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5291
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005292 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5293 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005294 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005295 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5296 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005297 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5298
5299 // Both windows are removed
5300 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5301 mWindow->consumeFocusEvent(false);
5302
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005303 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5304 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005305 mWindow->assertNoEvents();
5306}
5307
5308// Focus request can be pending until one window becomes visible.
5309TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5310 // Request focus on an invisible mirror.
5311 mWindow->setVisible(false);
5312 mMirror->setVisible(false);
5313 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5314 setFocusedWindow(mMirror);
5315
5316 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005317 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005318 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005319 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005320
5321 mMirror->setVisible(true);
5322 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5323
5324 // window gets focused
5325 mWindow->consumeFocusEvent(true);
5326 // window gets the pending key event
5327 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5328}
Prabir Pradhan99987712020-11-10 18:43:05 -08005329
5330class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5331protected:
5332 std::shared_ptr<FakeApplicationHandle> mApp;
5333 sp<FakeWindowHandle> mWindow;
5334 sp<FakeWindowHandle> mSecondWindow;
5335
5336 void SetUp() override {
5337 InputDispatcherTest::SetUp();
5338 mApp = std::make_shared<FakeApplicationHandle>();
5339 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5340 mWindow->setFocusable(true);
5341 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5342 mSecondWindow->setFocusable(true);
5343
5344 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5345 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5346
5347 setFocusedWindow(mWindow);
5348 mWindow->consumeFocusEvent(true);
5349 }
5350
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005351 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5352 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005353 mDispatcher->notifyPointerCaptureChanged(&args);
5354 }
5355
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005356 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5357 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005358 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005359 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5360 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005361 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005362 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005363 }
5364};
5365
5366TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5367 // Ensure that capture cannot be obtained for unfocused windows.
5368 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5369 mFakePolicy->assertSetPointerCaptureNotCalled();
5370 mSecondWindow->assertNoEvents();
5371
5372 // Ensure that capture can be enabled from the focus window.
5373 requestAndVerifyPointerCapture(mWindow, true);
5374
5375 // Ensure that capture cannot be disabled from a window that does not have capture.
5376 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5377 mFakePolicy->assertSetPointerCaptureNotCalled();
5378
5379 // Ensure that capture can be disabled from the window with capture.
5380 requestAndVerifyPointerCapture(mWindow, false);
5381}
5382
5383TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005384 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005385
5386 setFocusedWindow(mSecondWindow);
5387
5388 // Ensure that the capture disabled event was sent first.
5389 mWindow->consumeCaptureEvent(false);
5390 mWindow->consumeFocusEvent(false);
5391 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005392 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005393
5394 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005395 notifyPointerCaptureChanged({});
5396 notifyPointerCaptureChanged(request);
5397 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005398 mWindow->assertNoEvents();
5399 mSecondWindow->assertNoEvents();
5400 mFakePolicy->assertSetPointerCaptureNotCalled();
5401}
5402
5403TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005404 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005405
5406 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005407 notifyPointerCaptureChanged({});
5408 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005409
5410 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005411 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005412 mWindow->consumeCaptureEvent(false);
5413 mWindow->assertNoEvents();
5414}
5415
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005416TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5417 requestAndVerifyPointerCapture(mWindow, true);
5418
5419 // The first window loses focus.
5420 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005421 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005422 mWindow->consumeCaptureEvent(false);
5423
5424 // Request Pointer Capture from the second window before the notification from InputReader
5425 // arrives.
5426 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005427 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005428
5429 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005430 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005431
5432 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005433 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005434
5435 mSecondWindow->consumeFocusEvent(true);
5436 mSecondWindow->consumeCaptureEvent(true);
5437}
5438
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005439TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5440 // App repeatedly enables and disables capture.
5441 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5442 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5443 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5444 mFakePolicy->assertSetPointerCaptureCalled(false);
5445 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5446 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5447
5448 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5449 // first request is now stale, this should do nothing.
5450 notifyPointerCaptureChanged(firstRequest);
5451 mWindow->assertNoEvents();
5452
5453 // InputReader notifies that the second request was enabled.
5454 notifyPointerCaptureChanged(secondRequest);
5455 mWindow->consumeCaptureEvent(true);
5456}
5457
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005458class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5459protected:
5460 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005461
5462 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5463 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5464
5465 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5466 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5467
5468 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5469 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5470 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5471 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5472 MAXIMUM_OBSCURING_OPACITY);
5473
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005474 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005475 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005476 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005477
5478 sp<FakeWindowHandle> mTouchWindow;
5479
5480 virtual void SetUp() override {
5481 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005482 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005483 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5484 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5485 }
5486
5487 virtual void TearDown() override {
5488 InputDispatcherTest::TearDown();
5489 mTouchWindow.clear();
5490 }
5491
chaviw3277faf2021-05-19 16:45:23 -05005492 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5493 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005494 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005495 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005496 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005497 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005498 return window;
5499 }
5500
5501 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5502 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5503 sp<FakeWindowHandle> window =
5504 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5505 // Generate an arbitrary PID based on the UID
5506 window->setOwnerInfo(1777 + (uid % 10000), uid);
5507 return window;
5508 }
5509
5510 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5511 NotifyMotionArgs args =
5512 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5513 ADISPLAY_ID_DEFAULT, points);
5514 mDispatcher->notifyMotion(&args);
5515 }
5516};
5517
5518TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005519 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005520 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005521 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005522
5523 touch();
5524
5525 mTouchWindow->assertNoEvents();
5526}
5527
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005528TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005529 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5530 const sp<FakeWindowHandle>& w =
5531 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5532 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5533
5534 touch();
5535
5536 mTouchWindow->assertNoEvents();
5537}
5538
5539TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005540 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5541 const sp<FakeWindowHandle>& w =
5542 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5543 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5544
5545 touch();
5546
5547 w->assertNoEvents();
5548}
5549
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005550TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005551 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5552 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005553
5554 touch();
5555
5556 mTouchWindow->consumeAnyMotionDown();
5557}
5558
5559TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005560 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005561 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005562 w->setFrame(Rect(0, 0, 50, 50));
5563 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005564
5565 touch({PointF{100, 100}});
5566
5567 mTouchWindow->consumeAnyMotionDown();
5568}
5569
5570TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005571 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005572 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005573 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5574
5575 touch();
5576
5577 mTouchWindow->consumeAnyMotionDown();
5578}
5579
5580TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5581 const sp<FakeWindowHandle>& w =
5582 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5583 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005584
5585 touch();
5586
5587 mTouchWindow->consumeAnyMotionDown();
5588}
5589
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005590TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5591 const sp<FakeWindowHandle>& w =
5592 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5593 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5594
5595 touch();
5596
5597 w->assertNoEvents();
5598}
5599
5600/**
5601 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5602 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5603 * window, the occluding window will still receive ACTION_OUTSIDE event.
5604 */
5605TEST_F(InputDispatcherUntrustedTouchesTest,
5606 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5607 const sp<FakeWindowHandle>& w =
5608 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005609 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005610 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5611
5612 touch();
5613
5614 w->consumeMotionOutside();
5615}
5616
5617TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5618 const sp<FakeWindowHandle>& w =
5619 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005620 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005621 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5622
5623 touch();
5624
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005625 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005626}
5627
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005628TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005629 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005630 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5631 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005632 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5633
5634 touch();
5635
5636 mTouchWindow->consumeAnyMotionDown();
5637}
5638
5639TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5640 const sp<FakeWindowHandle>& w =
5641 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5642 MAXIMUM_OBSCURING_OPACITY);
5643 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005644
5645 touch();
5646
5647 mTouchWindow->consumeAnyMotionDown();
5648}
5649
5650TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005651 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005652 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5653 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005654 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5655
5656 touch();
5657
5658 mTouchWindow->assertNoEvents();
5659}
5660
5661TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5662 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5663 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005664 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5665 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005666 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005667 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5668 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005669 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5670
5671 touch();
5672
5673 mTouchWindow->assertNoEvents();
5674}
5675
5676TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5677 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5678 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005679 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5680 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005681 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005682 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5683 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005684 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5685
5686 touch();
5687
5688 mTouchWindow->consumeAnyMotionDown();
5689}
5690
5691TEST_F(InputDispatcherUntrustedTouchesTest,
5692 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5693 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005694 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5695 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005696 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005697 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5698 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005699 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5700
5701 touch();
5702
5703 mTouchWindow->consumeAnyMotionDown();
5704}
5705
5706TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5707 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005708 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5709 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005710 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005711 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5712 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005713 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005714
5715 touch();
5716
5717 mTouchWindow->assertNoEvents();
5718}
5719
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005720TEST_F(InputDispatcherUntrustedTouchesTest,
5721 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5722 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005723 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5724 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005725 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005726 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5727 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005728 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5729
5730 touch();
5731
5732 mTouchWindow->assertNoEvents();
5733}
5734
5735TEST_F(InputDispatcherUntrustedTouchesTest,
5736 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5737 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005738 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5739 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005740 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005741 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5742 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005743 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5744
5745 touch();
5746
5747 mTouchWindow->consumeAnyMotionDown();
5748}
5749
5750TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5751 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005752 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5753 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005754 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5755
5756 touch();
5757
5758 mTouchWindow->consumeAnyMotionDown();
5759}
5760
5761TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5762 const sp<FakeWindowHandle>& w =
5763 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5764 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5765
5766 touch();
5767
5768 mTouchWindow->consumeAnyMotionDown();
5769}
5770
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005771TEST_F(InputDispatcherUntrustedTouchesTest,
5772 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5773 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5774 const sp<FakeWindowHandle>& w =
5775 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5776 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5777
5778 touch();
5779
5780 mTouchWindow->assertNoEvents();
5781}
5782
5783TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5784 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5785 const sp<FakeWindowHandle>& w =
5786 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5787 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5788
5789 touch();
5790
5791 mTouchWindow->consumeAnyMotionDown();
5792}
5793
5794TEST_F(InputDispatcherUntrustedTouchesTest,
5795 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5796 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5797 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005798 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5799 OPACITY_ABOVE_THRESHOLD);
5800 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5801
5802 touch();
5803
5804 mTouchWindow->consumeAnyMotionDown();
5805}
5806
5807TEST_F(InputDispatcherUntrustedTouchesTest,
5808 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5809 const sp<FakeWindowHandle>& w1 =
5810 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5811 OPACITY_BELOW_THRESHOLD);
5812 const sp<FakeWindowHandle>& w2 =
5813 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5814 OPACITY_BELOW_THRESHOLD);
5815 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5816
5817 touch();
5818
5819 mTouchWindow->assertNoEvents();
5820}
5821
5822/**
5823 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5824 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5825 * (which alone would result in allowing touches) does not affect the blocking behavior.
5826 */
5827TEST_F(InputDispatcherUntrustedTouchesTest,
5828 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5829 const sp<FakeWindowHandle>& wB =
5830 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5831 OPACITY_BELOW_THRESHOLD);
5832 const sp<FakeWindowHandle>& wC =
5833 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5834 OPACITY_BELOW_THRESHOLD);
5835 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5836
5837 touch();
5838
5839 mTouchWindow->assertNoEvents();
5840}
5841
5842/**
5843 * This test is testing that a window from a different UID but with same application token doesn't
5844 * block the touch. Apps can share the application token for close UI collaboration for example.
5845 */
5846TEST_F(InputDispatcherUntrustedTouchesTest,
5847 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5848 const sp<FakeWindowHandle>& w =
5849 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5850 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005851 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5852
5853 touch();
5854
5855 mTouchWindow->consumeAnyMotionDown();
5856}
5857
arthurhungb89ccb02020-12-30 16:19:01 +08005858class InputDispatcherDragTests : public InputDispatcherTest {
5859protected:
5860 std::shared_ptr<FakeApplicationHandle> mApp;
5861 sp<FakeWindowHandle> mWindow;
5862 sp<FakeWindowHandle> mSecondWindow;
5863 sp<FakeWindowHandle> mDragWindow;
5864
5865 void SetUp() override {
5866 InputDispatcherTest::SetUp();
5867 mApp = std::make_shared<FakeApplicationHandle>();
5868 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5869 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005870 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005871
5872 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5873 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005874 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005875
5876 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5877 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5878 }
5879
5880 // Start performing drag, we will create a drag window and transfer touch to it.
5881 void performDrag() {
5882 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5883 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5884 {50, 50}))
5885 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5886
5887 // Window should receive motion event.
5888 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5889
5890 // The drag window covers the entire display
5891 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5892 mDispatcher->setInputWindows(
5893 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5894
5895 // Transfer touch focus to the drag window
5896 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5897 true /* isDragDrop */);
5898 mWindow->consumeMotionCancel();
5899 mDragWindow->consumeMotionDown();
5900 }
arthurhung6d4bed92021-03-17 11:59:33 +08005901
5902 // Start performing drag, we will create a drag window and transfer touch to it.
5903 void performStylusDrag() {
5904 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5905 injectMotionEvent(mDispatcher,
5906 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5907 AINPUT_SOURCE_STYLUS)
5908 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5909 .pointer(PointerBuilder(0,
5910 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5911 .x(50)
5912 .y(50))
5913 .build()));
5914 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5915
5916 // The drag window covers the entire display
5917 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5918 mDispatcher->setInputWindows(
5919 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5920
5921 // Transfer touch focus to the drag window
5922 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5923 true /* isDragDrop */);
5924 mWindow->consumeMotionCancel();
5925 mDragWindow->consumeMotionDown();
5926 }
arthurhungb89ccb02020-12-30 16:19:01 +08005927};
5928
5929TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5930 performDrag();
5931
5932 // Move on window.
5933 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5934 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5935 ADISPLAY_ID_DEFAULT, {50, 50}))
5936 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5937 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5938 mWindow->consumeDragEvent(false, 50, 50);
5939 mSecondWindow->assertNoEvents();
5940
5941 // Move to another window.
5942 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5943 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5944 ADISPLAY_ID_DEFAULT, {150, 50}))
5945 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5946 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5947 mWindow->consumeDragEvent(true, 150, 50);
5948 mSecondWindow->consumeDragEvent(false, 50, 50);
5949
5950 // Move back to original window.
5951 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5952 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5953 ADISPLAY_ID_DEFAULT, {50, 50}))
5954 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5955 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5956 mWindow->consumeDragEvent(false, 50, 50);
5957 mSecondWindow->consumeDragEvent(true, -50, 50);
5958
5959 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5960 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5961 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5962 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5963 mWindow->assertNoEvents();
5964 mSecondWindow->assertNoEvents();
5965}
5966
arthurhungf452d0b2021-01-06 00:19:52 +08005967TEST_F(InputDispatcherDragTests, DragAndDrop) {
5968 performDrag();
5969
5970 // Move on window.
5971 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5972 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5973 ADISPLAY_ID_DEFAULT, {50, 50}))
5974 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5975 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5976 mWindow->consumeDragEvent(false, 50, 50);
5977 mSecondWindow->assertNoEvents();
5978
5979 // Move to another window.
5980 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5981 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5982 ADISPLAY_ID_DEFAULT, {150, 50}))
5983 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5984 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5985 mWindow->consumeDragEvent(true, 150, 50);
5986 mSecondWindow->consumeDragEvent(false, 50, 50);
5987
5988 // drop to another window.
5989 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5990 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5991 {150, 50}))
5992 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5993 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5994 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5995 mWindow->assertNoEvents();
5996 mSecondWindow->assertNoEvents();
5997}
5998
arthurhung6d4bed92021-03-17 11:59:33 +08005999TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6000 performStylusDrag();
6001
6002 // Move on window and keep button pressed.
6003 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6004 injectMotionEvent(mDispatcher,
6005 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6006 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6007 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6008 .x(50)
6009 .y(50))
6010 .build()))
6011 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6012 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6013 mWindow->consumeDragEvent(false, 50, 50);
6014 mSecondWindow->assertNoEvents();
6015
6016 // Move to another window and release button, expect to drop item.
6017 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6018 injectMotionEvent(mDispatcher,
6019 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6020 .buttonState(0)
6021 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6022 .x(150)
6023 .y(50))
6024 .build()))
6025 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6026 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6027 mWindow->assertNoEvents();
6028 mSecondWindow->assertNoEvents();
6029 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6030
6031 // nothing to the window.
6032 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6033 injectMotionEvent(mDispatcher,
6034 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6035 .buttonState(0)
6036 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6037 .x(150)
6038 .y(50))
6039 .build()))
6040 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6041 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6042 mWindow->assertNoEvents();
6043 mSecondWindow->assertNoEvents();
6044}
6045
Arthur Hung6d0571e2021-04-09 20:18:16 +08006046TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6047 performDrag();
6048
6049 // Set second window invisible.
6050 mSecondWindow->setVisible(false);
6051 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6052
6053 // Move on window.
6054 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6055 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6056 ADISPLAY_ID_DEFAULT, {50, 50}))
6057 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6058 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6059 mWindow->consumeDragEvent(false, 50, 50);
6060 mSecondWindow->assertNoEvents();
6061
6062 // Move to another window.
6063 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6064 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6065 ADISPLAY_ID_DEFAULT, {150, 50}))
6066 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6067 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6068 mWindow->consumeDragEvent(true, 150, 50);
6069 mSecondWindow->assertNoEvents();
6070
6071 // drop to another window.
6072 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6073 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6074 {150, 50}))
6075 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6076 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6077 mFakePolicy->assertDropTargetEquals(nullptr);
6078 mWindow->assertNoEvents();
6079 mSecondWindow->assertNoEvents();
6080}
6081
Vishnu Nair062a8672021-09-03 16:07:44 -07006082class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6083
6084TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6085 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6086 sp<FakeWindowHandle> window =
6087 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6088 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
6089 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6090 window->setFocusable(true);
6091 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6092 setFocusedWindow(window);
6093 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6094
6095 // With the flag set, window should not get any input
6096 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6097 mDispatcher->notifyKey(&keyArgs);
6098 window->assertNoEvents();
6099
6100 NotifyMotionArgs motionArgs =
6101 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6102 ADISPLAY_ID_DEFAULT);
6103 mDispatcher->notifyMotion(&motionArgs);
6104 window->assertNoEvents();
6105
6106 // With the flag cleared, the window should get input
6107 window->setInputFeatures({});
6108 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6109
6110 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6111 mDispatcher->notifyKey(&keyArgs);
6112 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6113
6114 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6115 ADISPLAY_ID_DEFAULT);
6116 mDispatcher->notifyMotion(&motionArgs);
6117 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6118 window->assertNoEvents();
6119}
6120
6121TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6122 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6123 std::make_shared<FakeApplicationHandle>();
6124 sp<FakeWindowHandle> obscuringWindow =
6125 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6126 ADISPLAY_ID_DEFAULT);
6127 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6128 obscuringWindow->setOwnerInfo(111, 111);
6129 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6130 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6131 sp<FakeWindowHandle> window =
6132 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6133 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6134 window->setOwnerInfo(222, 222);
6135 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6136 window->setFocusable(true);
6137 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6138 setFocusedWindow(window);
6139 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6140
6141 // With the flag set, window should not get any input
6142 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6143 mDispatcher->notifyKey(&keyArgs);
6144 window->assertNoEvents();
6145
6146 NotifyMotionArgs motionArgs =
6147 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6148 ADISPLAY_ID_DEFAULT);
6149 mDispatcher->notifyMotion(&motionArgs);
6150 window->assertNoEvents();
6151
6152 // With the flag cleared, the window should get input
6153 window->setInputFeatures({});
6154 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6155
6156 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6157 mDispatcher->notifyKey(&keyArgs);
6158 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6159
6160 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6161 ADISPLAY_ID_DEFAULT);
6162 mDispatcher->notifyMotion(&motionArgs);
6163 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6164 window->assertNoEvents();
6165}
6166
6167TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6168 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6169 std::make_shared<FakeApplicationHandle>();
6170 sp<FakeWindowHandle> obscuringWindow =
6171 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6172 ADISPLAY_ID_DEFAULT);
6173 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6174 obscuringWindow->setOwnerInfo(111, 111);
6175 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6176 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6177 sp<FakeWindowHandle> window =
6178 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6179 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6180 window->setOwnerInfo(222, 222);
6181 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6182 window->setFocusable(true);
6183 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6184 setFocusedWindow(window);
6185 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6186
6187 // With the flag set, window should not get any input
6188 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6189 mDispatcher->notifyKey(&keyArgs);
6190 window->assertNoEvents();
6191
6192 NotifyMotionArgs motionArgs =
6193 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6194 ADISPLAY_ID_DEFAULT);
6195 mDispatcher->notifyMotion(&motionArgs);
6196 window->assertNoEvents();
6197
6198 // When the window is no longer obscured because it went on top, it should get input
6199 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6200
6201 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6202 mDispatcher->notifyKey(&keyArgs);
6203 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6204
6205 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6206 ADISPLAY_ID_DEFAULT);
6207 mDispatcher->notifyMotion(&motionArgs);
6208 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6209 window->assertNoEvents();
6210}
6211
Antonio Kantekf16f2832021-09-28 04:39:20 +00006212class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6213protected:
6214 std::shared_ptr<FakeApplicationHandle> mApp;
6215 sp<FakeWindowHandle> mWindow;
6216 sp<FakeWindowHandle> mSecondWindow;
6217
6218 void SetUp() override {
6219 InputDispatcherTest::SetUp();
6220
6221 mApp = std::make_shared<FakeApplicationHandle>();
6222 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6223 mWindow->setFocusable(true);
6224 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6225 mSecondWindow->setFocusable(true);
6226
6227 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6228 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6229
6230 setFocusedWindow(mWindow);
6231 mWindow->consumeFocusEvent(true);
6232 }
6233
6234 void changeAndVerifyTouchMode(bool inTouchMode) {
6235 mDispatcher->setInTouchMode(inTouchMode);
6236 mWindow->consumeTouchModeEvent(inTouchMode);
6237 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6238 }
6239};
6240
6241TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
6242 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode);
6243}
6244
6245TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
6246 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode);
6247 mWindow->assertNoEvents();
6248 mSecondWindow->assertNoEvents();
6249}
6250
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006251class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6252public:
6253 sp<FakeWindowHandle> createSpy(const Flags<WindowInfo::Flag> flags) {
6254 std::shared_ptr<FakeApplicationHandle> application =
6255 std::make_shared<FakeApplicationHandle>();
6256 std::string name = "Fake Spy ";
6257 name += std::to_string(mSpyCount++);
6258 sp<FakeWindowHandle> spy =
6259 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
6260 spy->setInputFeatures(WindowInfo::Feature::SPY);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006261 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006262 spy->addFlags(flags);
6263 return spy;
6264 }
6265
6266 sp<FakeWindowHandle> createForeground() {
6267 std::shared_ptr<FakeApplicationHandle> application =
6268 std::make_shared<FakeApplicationHandle>();
6269 sp<FakeWindowHandle> window =
6270 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
6271 window->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006272 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006273 return window;
6274 }
6275
6276private:
6277 int mSpyCount{0};
6278};
6279
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006280using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006281/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006282 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6283 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006284TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6285 ScopedSilentDeath _silentDeath;
6286
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006287 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6288 spy->setTrustedOverlay(false);
6289 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6290 ".* not a trusted overlay");
6291}
6292
6293/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006294 * Input injection into a display with a spy window but no foreground windows should succeed.
6295 */
6296TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
6297 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6298 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6299
6300 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6301 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6302 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6303 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6304}
6305
6306/**
6307 * Verify the order in which different input windows receive events. The touched foreground window
6308 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6309 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6310 * receive events before ones belows it.
6311 *
6312 * Here, we set up a scenario with four windows in the following Z order from the top:
6313 * spy1, spy2, window, spy3.
6314 * We then inject an event and verify that the foreground "window" receives it first, followed by
6315 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6316 * window.
6317 */
6318TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6319 auto window = createForeground();
6320 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6321 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6322 auto spy3 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6323 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6324 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6325 const size_t numChannels = channels.size();
6326
6327 base::unique_fd epollFd(epoll_create1(0 /*flags*/));
6328 if (!epollFd.ok()) {
6329 FAIL() << "Failed to create epoll fd";
6330 }
6331
6332 for (size_t i = 0; i < numChannels; i++) {
6333 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6334 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6335 FAIL() << "Failed to add fd to epoll";
6336 }
6337 }
6338
6339 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6340 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6341 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6342
6343 std::vector<size_t> eventOrder;
6344 std::vector<struct epoll_event> events(numChannels);
6345 for (;;) {
6346 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6347 (100ms).count());
6348 if (nFds < 0) {
6349 FAIL() << "Failed to call epoll_wait";
6350 }
6351 if (nFds == 0) {
6352 break; // epoll_wait timed out
6353 }
6354 for (int i = 0; i < nFds; i++) {
6355 ASSERT_EQ(EPOLLIN, events[i].events);
6356 eventOrder.push_back(events[i].data.u64);
6357 channels[i]->consumeMotionDown();
6358 }
6359 }
6360
6361 // Verify the order in which the events were received.
6362 EXPECT_EQ(3u, eventOrder.size());
6363 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6364 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6365 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6366}
6367
6368/**
6369 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6370 */
6371TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6372 auto window = createForeground();
6373 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCHABLE);
6374 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6375
6376 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6377 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6378 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6379 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6380 spy->assertNoEvents();
6381}
6382
6383/**
6384 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6385 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6386 * to the window.
6387 */
6388TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6389 auto window = createForeground();
6390 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6391 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6392 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6393
6394 // Inject an event outside the spy window's touchable region.
6395 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6396 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6397 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6398 window->consumeMotionDown();
6399 spy->assertNoEvents();
6400 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6401 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6402 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6403 window->consumeMotionUp();
6404 spy->assertNoEvents();
6405
6406 // Inject an event inside the spy window's touchable region.
6407 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6408 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6409 {5, 10}))
6410 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6411 window->consumeMotionDown();
6412 spy->consumeMotionDown();
6413}
6414
6415/**
6416 * A spy window that is a modal window will receive gestures outside of its frame and touchable
6417 * region.
6418 */
6419TEST_F(InputDispatcherSpyWindowTest, ModalWindow) {
6420 auto window = createForeground();
6421 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6422 // This spy window does not have the NOT_TOUCH_MODAL flag set.
6423 spy->setFrame(Rect{0, 0, 20, 20});
6424 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6425
6426 // Inject an event outside the spy window's frame and touchable region.
6427 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6428 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6429 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6430 window->consumeMotionDown();
6431 spy->consumeMotionDown();
6432}
6433
6434/**
6435 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006436 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006437 */
6438TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6439 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006440 window->setOwnerInfo(12, 34);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006441 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006442 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006443 spy->setFrame(Rect{0, 0, 20, 20});
6444 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6445
6446 // Inject an event outside the spy window's frame and touchable region.
6447 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006448 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6449 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006450 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6451 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006452 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006453}
6454
6455/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006456 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6457 * any other windows - including other spy windows - will also be cancelled.
6458 */
6459TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6460 auto window = createForeground();
6461 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6462 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6463 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6464
6465 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6466 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6467 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6468 window->consumeMotionDown();
6469 spy1->consumeMotionDown();
6470 spy2->consumeMotionDown();
6471
6472 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006473 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006474 spy2->assertNoEvents();
6475 spy1->consumeMotionCancel();
6476 window->consumeMotionCancel();
6477
6478 // The rest of the gesture should only be sent to the second spy window.
6479 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6480 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6481 ADISPLAY_ID_DEFAULT))
6482 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6483 spy2->consumeMotionMove();
6484 spy1->assertNoEvents();
6485 window->assertNoEvents();
6486}
6487
6488/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006489 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
6490 * in the middle of the gesture.
6491 */
6492TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
6493 auto window = createForeground();
6494 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6495 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6496
6497 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6498 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6499 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6500 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6501 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6502
6503 window->releaseChannel();
6504
6505 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6506
6507 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6508 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6509 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6510 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6511}
6512
6513/**
6514 * After a spy window pilfers pointers, new pointers that go down should not go to any foreground
6515 * windows.
6516 */
6517TEST_F(InputDispatcherSpyWindowTest, NoSplitAfterPilfer) {
6518 // Create a touch modal spy that spies on the entire display.
6519 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6520
6521 // Create a non touch modal window that supports split touch.
6522 auto window = createForeground();
6523 window->setFrame(Rect(0, 0, 100, 100));
6524 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
6525
6526 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6527
6528 // First finger down, no window touched.
6529 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6530 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6531 {100, 200}))
6532 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6533 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6534 window->assertNoEvents();
6535
6536 // Spy window pilfer the pointers.
6537 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6538
6539 // Second finger down on window, the window should not receive touch down.
6540 const MotionEvent secondFingerDownEvent =
6541 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6542 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6543 AINPUT_SOURCE_TOUCHSCREEN)
6544 .displayId(ADISPLAY_ID_DEFAULT)
6545 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6546 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6547 .x(100)
6548 .y(200))
6549 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6550 .build();
6551 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6552 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6553 InputEventInjectionSync::WAIT_FOR_RESULT))
6554 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6555
6556 window->assertNoEvents();
6557 // Since we no longer allow splitting, the spy will not receive new pointers.
6558 // TODO(b/217376964): Add a way for the pilfering window to receive the rest of the gesture.
6559 spy->consumeMotionMove();
6560}
6561
6562/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006563 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6564 * pointers that are down within its bounds.
6565 */
6566TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6567 auto windowLeft = createForeground();
6568 windowLeft->setFrame({0, 0, 100, 200});
6569 auto windowRight = createForeground();
6570 windowRight->setFrame({100, 0, 200, 200});
6571 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6572 spy->setFrame({0, 0, 200, 200});
6573 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6574
6575 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6576 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6577 {50, 50}))
6578 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6579 windowLeft->consumeMotionDown();
6580 spy->consumeMotionDown();
6581
6582 const MotionEvent secondFingerDownEvent =
6583 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6584 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6585 AINPUT_SOURCE_TOUCHSCREEN)
6586 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6587 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6588 .pointer(
6589 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6590 .build();
6591 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6592 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6593 InputEventInjectionSync::WAIT_FOR_RESULT))
6594 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6595 windowRight->consumeMotionDown();
6596 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6597}
6598
6599/**
6600 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6601 * the spy should receive the second pointer with ACTION_DOWN.
6602 */
6603TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6604 auto window = createForeground();
6605 window->setFrame({0, 0, 200, 200});
6606 auto spyRight = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6607 spyRight->setFrame({100, 0, 200, 200});
6608 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6609
6610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6611 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6612 {50, 50}))
6613 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6614 window->consumeMotionDown();
6615 spyRight->assertNoEvents();
6616
6617 const MotionEvent secondFingerDownEvent =
6618 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6619 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6620 AINPUT_SOURCE_TOUCHSCREEN)
6621 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6622 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6623 .pointer(
6624 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6625 .build();
6626 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6627 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6628 InputEventInjectionSync::WAIT_FOR_RESULT))
6629 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6630 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6631 spyRight->consumeMotionDown();
6632}
6633
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006634/**
6635 * The spy window should not be able to affect whether or not touches are split. Only the foreground
6636 * windows should be allowed to control split touch.
6637 */
6638TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
6639 // Create a touch modal spy that spies on the entire display.
6640 // This spy window does not set the SPLIT_TOUCH flag. However, we still expect to split touches
6641 // because a foreground window has not disabled splitting.
6642 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6643
6644 // Create a non touch modal window that supports split touch.
6645 auto window = createForeground();
6646 window->setFrame(Rect(0, 0, 100, 100));
6647 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
6648
6649 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6650
6651 // First finger down, no window touched.
6652 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6653 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6654 {100, 200}))
6655 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6656 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6657 window->assertNoEvents();
6658
6659 // Second finger down on window, the window should receive touch down.
6660 const MotionEvent secondFingerDownEvent =
6661 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6662 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6663 AINPUT_SOURCE_TOUCHSCREEN)
6664 .displayId(ADISPLAY_ID_DEFAULT)
6665 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6666 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6667 .x(100)
6668 .y(200))
6669 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6670 .build();
6671 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6672 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6673 InputEventInjectionSync::WAIT_FOR_RESULT))
6674 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6675
6676 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6677 spy->consumeMotionPointerDown(1 /* pointerIndex */);
6678}
6679
6680/**
6681 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
6682 * do not receive key events.
6683 */
6684TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
6685 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6686 spy->setFocusable(false);
6687
6688 auto window = createForeground();
6689 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6690 setFocusedWindow(window);
6691 window->consumeFocusEvent(true);
6692
6693 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6694 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6695 window->consumeKeyDown(ADISPLAY_ID_NONE);
6696
6697 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6698 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6699 window->consumeKeyUp(ADISPLAY_ID_NONE);
6700
6701 spy->assertNoEvents();
6702}
6703
Prabir Pradhand65552b2021-10-07 11:23:50 -07006704class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6705public:
6706 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6707 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6708 std::make_shared<FakeApplicationHandle>();
6709 sp<FakeWindowHandle> overlay =
6710 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6711 ADISPLAY_ID_DEFAULT);
6712 overlay->setFocusable(false);
6713 overlay->setOwnerInfo(111, 111);
6714 overlay->setFlags(WindowInfo::Flag::NOT_TOUCHABLE | WindowInfo::Flag::SPLIT_TOUCH);
6715 overlay->setInputFeatures(WindowInfo::Feature::INTERCEPTS_STYLUS);
6716 overlay->setTrustedOverlay(true);
6717
6718 std::shared_ptr<FakeApplicationHandle> application =
6719 std::make_shared<FakeApplicationHandle>();
6720 sp<FakeWindowHandle> window =
6721 new FakeWindowHandle(application, mDispatcher, "Application window",
6722 ADISPLAY_ID_DEFAULT);
6723 window->setFocusable(true);
6724 window->setOwnerInfo(222, 222);
6725 window->setFlags(WindowInfo::Flag::SPLIT_TOUCH);
6726
6727 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6728 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6729 setFocusedWindow(window);
6730 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6731 return {std::move(overlay), std::move(window)};
6732 }
6733
6734 void sendFingerEvent(int32_t action) {
6735 NotifyMotionArgs motionArgs =
6736 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6737 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6738 mDispatcher->notifyMotion(&motionArgs);
6739 }
6740
6741 void sendStylusEvent(int32_t action) {
6742 NotifyMotionArgs motionArgs =
6743 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6744 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6745 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6746 mDispatcher->notifyMotion(&motionArgs);
6747 }
6748};
6749
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006750using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
6751
6752TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
6753 ScopedSilentDeath _silentDeath;
6754
Prabir Pradhand65552b2021-10-07 11:23:50 -07006755 auto [overlay, window] = setupStylusOverlayScenario();
6756 overlay->setTrustedOverlay(false);
6757 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6758 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6759 ".* not a trusted overlay");
6760}
6761
6762TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6763 auto [overlay, window] = setupStylusOverlayScenario();
6764 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6765
6766 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6767 overlay->consumeMotionDown();
6768 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6769 overlay->consumeMotionUp();
6770
6771 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6772 window->consumeMotionDown();
6773 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6774 window->consumeMotionUp();
6775
6776 overlay->assertNoEvents();
6777 window->assertNoEvents();
6778}
6779
6780TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6781 auto [overlay, window] = setupStylusOverlayScenario();
6782 overlay->setInputFeatures(overlay->getInfo()->inputFeatures | WindowInfo::Feature::SPY);
6783 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6784
6785 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6786 overlay->consumeMotionDown();
6787 window->consumeMotionDown();
6788 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6789 overlay->consumeMotionUp();
6790 window->consumeMotionUp();
6791
6792 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6793 window->consumeMotionDown();
6794 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6795 window->consumeMotionUp();
6796
6797 overlay->assertNoEvents();
6798 window->assertNoEvents();
6799}
6800
Garfield Tane84e6f92019-08-29 17:28:41 -07006801} // namespace android::inputdispatcher