blob: ccdde6eccd7018edbc63ccabfc511ebbd5cb4254 [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
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001130 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1131 ASSERT_NE(mInputReceiver, nullptr)
1132 << "Cannot consume events from a window with no receiver";
1133 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1134 }
1135
Prabir Pradhan99987712020-11-10 18:43:05 -08001136 void consumeCaptureEvent(bool hasCapture) {
1137 ASSERT_NE(mInputReceiver, nullptr)
1138 << "Cannot consume events from a window with no receiver";
1139 mInputReceiver->consumeCaptureEvent(hasCapture);
1140 }
1141
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001142 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1143 std::optional<int32_t> expectedDisplayId,
1144 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001145 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1146 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1147 expectedFlags);
1148 }
1149
arthurhungb89ccb02020-12-30 16:19:01 +08001150 void consumeDragEvent(bool isExiting, float x, float y) {
1151 mInputReceiver->consumeDragEvent(isExiting, x, y);
1152 }
1153
Antonio Kantekf16f2832021-09-28 04:39:20 +00001154 void consumeTouchModeEvent(bool inTouchMode) {
1155 ASSERT_NE(mInputReceiver, nullptr)
1156 << "Cannot consume events from a window with no receiver";
1157 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1158 }
1159
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001160 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001161 if (mInputReceiver == nullptr) {
1162 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1163 return std::nullopt;
1164 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001165 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001166 }
1167
1168 void finishEvent(uint32_t sequenceNum) {
1169 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1170 mInputReceiver->finishEvent(sequenceNum);
1171 }
1172
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001173 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1174 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1175 mInputReceiver->sendTimeline(inputEventId, timeline);
1176 }
1177
chaviwaf87b3e2019-10-01 16:59:28 -07001178 InputEvent* consume() {
1179 if (mInputReceiver == nullptr) {
1180 return nullptr;
1181 }
1182 return mInputReceiver->consume();
1183 }
1184
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001185 MotionEvent* consumeMotion() {
1186 InputEvent* event = consume();
1187 if (event == nullptr) {
1188 ADD_FAILURE() << "Consume failed : no event";
1189 return nullptr;
1190 }
1191 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1192 ADD_FAILURE() << "Instead of motion event, got "
1193 << inputEventTypeToString(event->getType());
1194 return nullptr;
1195 }
1196 return static_cast<MotionEvent*>(event);
1197 }
1198
Arthur Hungb92218b2018-08-14 12:00:21 +08001199 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001200 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001201 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001202 return; // Can't receive events if the window does not have input channel
1203 }
1204 ASSERT_NE(nullptr, mInputReceiver)
1205 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001206 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001207 }
1208
chaviwaf87b3e2019-10-01 16:59:28 -07001209 sp<IBinder> getToken() { return mInfo.token; }
1210
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001211 const std::string& getName() { return mName; }
1212
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001213 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1214 mInfo.ownerPid = ownerPid;
1215 mInfo.ownerUid = ownerUid;
1216 }
1217
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001218 void destroyReceiver() { mInputReceiver = nullptr; }
1219
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001220 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1221
chaviwd1c23182019-12-20 18:44:56 -08001222private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001223 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001224 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001225 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001226};
1227
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001228std::atomic<int32_t> FakeWindowHandle::sId{1};
1229
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001230static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001231 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001232 int32_t displayId = ADISPLAY_ID_NONE,
1233 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001234 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1235 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001236 KeyEvent event;
1237 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1238
1239 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001240 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001241 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1242 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001243
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001244 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1245 if (!allowKeyRepeat) {
1246 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1247 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001248 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001249 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001250 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001251}
1252
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001253static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001254 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001255 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1256}
1257
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001258// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1259// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1260// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001261static InputEventInjectionResult injectKeyDownNoRepeat(
1262 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001263 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1264 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1265 /* allowKeyRepeat */ false);
1266}
1267
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001268static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001269 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001270 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1271}
1272
Garfield Tandf26e862020-07-01 20:18:19 -07001273class PointerBuilder {
1274public:
1275 PointerBuilder(int32_t id, int32_t toolType) {
1276 mProperties.clear();
1277 mProperties.id = id;
1278 mProperties.toolType = toolType;
1279 mCoords.clear();
1280 }
1281
1282 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1283
1284 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1285
1286 PointerBuilder& axis(int32_t axis, float value) {
1287 mCoords.setAxisValue(axis, value);
1288 return *this;
1289 }
1290
1291 PointerProperties buildProperties() const { return mProperties; }
1292
1293 PointerCoords buildCoords() const { return mCoords; }
1294
1295private:
1296 PointerProperties mProperties;
1297 PointerCoords mCoords;
1298};
1299
1300class MotionEventBuilder {
1301public:
1302 MotionEventBuilder(int32_t action, int32_t source) {
1303 mAction = action;
1304 mSource = source;
1305 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1306 }
1307
1308 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1309 mEventTime = eventTime;
1310 return *this;
1311 }
1312
1313 MotionEventBuilder& displayId(int32_t displayId) {
1314 mDisplayId = displayId;
1315 return *this;
1316 }
1317
1318 MotionEventBuilder& actionButton(int32_t actionButton) {
1319 mActionButton = actionButton;
1320 return *this;
1321 }
1322
arthurhung6d4bed92021-03-17 11:59:33 +08001323 MotionEventBuilder& buttonState(int32_t buttonState) {
1324 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001325 return *this;
1326 }
1327
1328 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1329 mRawXCursorPosition = rawXCursorPosition;
1330 return *this;
1331 }
1332
1333 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1334 mRawYCursorPosition = rawYCursorPosition;
1335 return *this;
1336 }
1337
1338 MotionEventBuilder& pointer(PointerBuilder pointer) {
1339 mPointers.push_back(pointer);
1340 return *this;
1341 }
1342
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001343 MotionEventBuilder& addFlag(uint32_t flags) {
1344 mFlags |= flags;
1345 return *this;
1346 }
1347
Garfield Tandf26e862020-07-01 20:18:19 -07001348 MotionEvent build() {
1349 std::vector<PointerProperties> pointerProperties;
1350 std::vector<PointerCoords> pointerCoords;
1351 for (const PointerBuilder& pointer : mPointers) {
1352 pointerProperties.push_back(pointer.buildProperties());
1353 pointerCoords.push_back(pointer.buildCoords());
1354 }
1355
1356 // Set mouse cursor position for the most common cases to avoid boilerplate.
1357 if (mSource == AINPUT_SOURCE_MOUSE &&
1358 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1359 mPointers.size() == 1) {
1360 mRawXCursorPosition = pointerCoords[0].getX();
1361 mRawYCursorPosition = pointerCoords[0].getY();
1362 }
1363
1364 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001365 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001366 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001367 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001368 mButtonState, MotionClassification::NONE, identityTransform,
1369 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001370 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1371 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001372
1373 return event;
1374 }
1375
1376private:
1377 int32_t mAction;
1378 int32_t mSource;
1379 nsecs_t mEventTime;
1380 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1381 int32_t mActionButton{0};
1382 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001383 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001384 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1385 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1386
1387 std::vector<PointerBuilder> mPointers;
1388};
1389
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001390static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001391 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001392 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001393 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001394 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1395 injectionTimeout,
1396 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1397}
1398
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001399static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001400 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001401 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001402 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001403 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1404 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001405 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001406 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001407 MotionEvent event = MotionEventBuilder(action, source)
1408 .displayId(displayId)
1409 .eventTime(eventTime)
1410 .rawXCursorPosition(cursorPosition.x)
1411 .rawYCursorPosition(cursorPosition.y)
1412 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1413 .x(position.x)
1414 .y(position.y))
1415 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001416
1417 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001418 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001419}
1420
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001421static InputEventInjectionResult injectMotionDown(
1422 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1423 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001424 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001425}
1426
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001427static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001428 int32_t source, int32_t displayId,
1429 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001430 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001431}
1432
Jackal Guof9696682018-10-05 12:23:23 +08001433static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1434 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1435 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001436 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1437 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1438 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001439
1440 return args;
1441}
1442
chaviwd1c23182019-12-20 18:44:56 -08001443static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1444 const std::vector<PointF>& points) {
1445 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001446 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1447 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1448 }
1449
chaviwd1c23182019-12-20 18:44:56 -08001450 PointerProperties pointerProperties[pointerCount];
1451 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001452
chaviwd1c23182019-12-20 18:44:56 -08001453 for (size_t i = 0; i < pointerCount; i++) {
1454 pointerProperties[i].clear();
1455 pointerProperties[i].id = i;
1456 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001457
chaviwd1c23182019-12-20 18:44:56 -08001458 pointerCoords[i].clear();
1459 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1460 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1461 }
Jackal Guof9696682018-10-05 12:23:23 +08001462
1463 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1464 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001465 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001466 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1467 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001468 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1469 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001470 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1471 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001472
1473 return args;
1474}
1475
chaviwd1c23182019-12-20 18:44:56 -08001476static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1477 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1478}
1479
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001480static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1481 const PointerCaptureRequest& request) {
1482 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001483}
1484
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001485/**
1486 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1487 * broken channel.
1488 */
1489TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1490 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1491 sp<FakeWindowHandle> window =
1492 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1493 ADISPLAY_ID_DEFAULT);
1494
1495 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1496
1497 // Window closes its channel, but the window remains.
1498 window->destroyReceiver();
1499 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1500}
1501
Arthur Hungb92218b2018-08-14 12:00:21 +08001502TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001503 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001504 sp<FakeWindowHandle> window =
1505 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001506
Arthur Hung72d8dc32020-03-28 00:48:39 +00001507 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001508 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1509 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1510 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001511
1512 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001513 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001514}
1515
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001516TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1517 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1518 sp<FakeWindowHandle> window =
1519 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1520
1521 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1522 // Inject a MotionEvent to an unknown display.
1523 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1524 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1525 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1526
1527 // Window should receive motion event.
1528 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1529}
1530
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001531/**
1532 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1533 * To ensure that window receives only events that were directly inside of it, add
1534 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1535 * when finding touched windows.
1536 * This test serves as a sanity check for the next test, where setInputWindows is
1537 * called twice.
1538 */
1539TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001540 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001541 sp<FakeWindowHandle> window =
1542 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1543 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001544 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001545
1546 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001547 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001548 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1549 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001550 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001551
1552 // Window should receive motion event.
1553 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1554}
1555
1556/**
1557 * Calling setInputWindows twice, with the same info, should not cause any issues.
1558 * To ensure that window receives only events that were directly inside of it, add
1559 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1560 * when finding touched windows.
1561 */
1562TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001563 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001564 sp<FakeWindowHandle> window =
1565 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1566 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001567 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001568
1569 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1570 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001571 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001572 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1573 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001574 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001575
1576 // Window should receive motion event.
1577 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1578}
1579
Arthur Hungb92218b2018-08-14 12:00:21 +08001580// The foreground window should receive the first touch down event.
1581TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001582 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001583 sp<FakeWindowHandle> windowTop =
1584 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1585 sp<FakeWindowHandle> windowSecond =
1586 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001587
Arthur Hung72d8dc32020-03-28 00:48:39 +00001588 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001589 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1590 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1591 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001592
1593 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001594 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001595 windowSecond->assertNoEvents();
1596}
1597
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001598/**
1599 * Two windows: A top window, and a wallpaper behind the window.
1600 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1601 * gets ACTION_CANCEL.
1602 * 1. foregroundWindow <-- has wallpaper (hasWallpaper=true)
1603 * 2. wallpaperWindow <-- is wallpaper (type=InputWindowInfo::Type::WALLPAPER)
1604 */
1605TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1606 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1607 sp<FakeWindowHandle> foregroundWindow =
1608 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1609 foregroundWindow->setHasWallpaper(true);
1610 sp<FakeWindowHandle> wallpaperWindow =
1611 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1612 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1613 constexpr int expectedWallpaperFlags =
1614 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1615
1616 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1618 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1619 {100, 200}))
1620 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1621
1622 // Both foreground window and its wallpaper should receive the touch down
1623 foregroundWindow->consumeMotionDown();
1624 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1625
1626 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1627 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1628 ADISPLAY_ID_DEFAULT, {110, 200}))
1629 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1630
1631 foregroundWindow->consumeMotionMove();
1632 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1633
1634 // Now the foreground window goes away, but the wallpaper stays
1635 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1636 foregroundWindow->consumeMotionCancel();
1637 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1638 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1639}
1640
1641/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001642 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1643 * with the following differences:
1644 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1645 * clean up the connection.
1646 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1647 * Ensure that there's no crash in the dispatcher.
1648 */
1649TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1650 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1651 sp<FakeWindowHandle> foregroundWindow =
1652 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1653 foregroundWindow->setHasWallpaper(true);
1654 sp<FakeWindowHandle> wallpaperWindow =
1655 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1656 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1657 constexpr int expectedWallpaperFlags =
1658 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1659
1660 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1661 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1662 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1663 {100, 200}))
1664 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1665
1666 // Both foreground window and its wallpaper should receive the touch down
1667 foregroundWindow->consumeMotionDown();
1668 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1669
1670 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1671 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1672 ADISPLAY_ID_DEFAULT, {110, 200}))
1673 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1674
1675 foregroundWindow->consumeMotionMove();
1676 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1677
1678 // Wallpaper closes its channel, but the window remains.
1679 wallpaperWindow->destroyReceiver();
1680 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1681
1682 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1683 // is no longer valid.
1684 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1685 foregroundWindow->consumeMotionCancel();
1686}
1687
1688/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001689 * A single window that receives touch (on top), and a wallpaper window underneath it.
1690 * The top window gets a multitouch gesture.
1691 * Ensure that wallpaper gets the same gesture.
1692 */
1693TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1694 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1695 sp<FakeWindowHandle> window =
1696 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1697 window->setHasWallpaper(true);
1698
1699 sp<FakeWindowHandle> wallpaperWindow =
1700 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1701 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1702 constexpr int expectedWallpaperFlags =
1703 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1704
1705 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1706
1707 // Touch down on top window
1708 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1709 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1710 {100, 100}))
1711 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1712
1713 // Both top window and its wallpaper should receive the touch down
1714 window->consumeMotionDown();
1715 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1716
1717 // Second finger down on the top window
1718 const MotionEvent secondFingerDownEvent =
1719 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1720 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1721 AINPUT_SOURCE_TOUCHSCREEN)
1722 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1723 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1724 .x(100)
1725 .y(100))
1726 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1727 .x(150)
1728 .y(150))
1729 .build();
1730 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1731 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1732 InputEventInjectionSync::WAIT_FOR_RESULT))
1733 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1734
1735 window->consumeMotionPointerDown(1 /* pointerIndex */);
1736 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1737 expectedWallpaperFlags);
1738 window->assertNoEvents();
1739 wallpaperWindow->assertNoEvents();
1740}
1741
1742/**
1743 * Two windows: a window on the left and window on the right.
1744 * A third window, wallpaper, is behind both windows, and spans both top windows.
1745 * The first touch down goes to the left window. A second pointer touches down on the right window.
1746 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1747 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1748 * ACTION_POINTER_DOWN(1).
1749 */
1750TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1751 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1752 sp<FakeWindowHandle> leftWindow =
1753 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1754 leftWindow->setFrame(Rect(0, 0, 200, 200));
1755 leftWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1756 leftWindow->setHasWallpaper(true);
1757
1758 sp<FakeWindowHandle> rightWindow =
1759 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1760 rightWindow->setFrame(Rect(200, 0, 400, 200));
1761 rightWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1762 rightWindow->setHasWallpaper(true);
1763
1764 sp<FakeWindowHandle> wallpaperWindow =
1765 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1766 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
1767 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1768 constexpr int expectedWallpaperFlags =
1769 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1770
1771 mDispatcher->setInputWindows(
1772 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1773
1774 // Touch down on left window
1775 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1776 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1777 {100, 100}))
1778 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1779
1780 // Both foreground window and its wallpaper should receive the touch down
1781 leftWindow->consumeMotionDown();
1782 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1783
1784 // Second finger down on the right window
1785 const MotionEvent secondFingerDownEvent =
1786 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1787 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1788 AINPUT_SOURCE_TOUCHSCREEN)
1789 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1790 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1791 .x(100)
1792 .y(100))
1793 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1794 .x(300)
1795 .y(100))
1796 .build();
1797 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1798 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1799 InputEventInjectionSync::WAIT_FOR_RESULT))
1800 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1801
1802 leftWindow->consumeMotionMove();
1803 // Since the touch is split, right window gets ACTION_DOWN
1804 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1805 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1806 expectedWallpaperFlags);
1807
1808 // Now, leftWindow, which received the first finger, disappears.
1809 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1810 leftWindow->consumeMotionCancel();
1811 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1812 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1813
1814 // The pointer that's still down on the right window moves, and goes to the right window only.
1815 // As far as the dispatcher's concerned though, both pointers are still present.
1816 const MotionEvent secondFingerMoveEvent =
1817 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1818 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1819 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1820 .x(100)
1821 .y(100))
1822 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1823 .x(310)
1824 .y(110))
1825 .build();
1826 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1827 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1828 InputEventInjectionSync::WAIT_FOR_RESULT));
1829 rightWindow->consumeMotionMove();
1830
1831 leftWindow->assertNoEvents();
1832 rightWindow->assertNoEvents();
1833 wallpaperWindow->assertNoEvents();
1834}
1835
Garfield Tandf26e862020-07-01 20:18:19 -07001836TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001837 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001838 sp<FakeWindowHandle> windowLeft =
1839 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1840 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001841 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001842 sp<FakeWindowHandle> windowRight =
1843 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1844 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001845 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001846
1847 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1848
1849 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1850
1851 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001852 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001853 injectMotionEvent(mDispatcher,
1854 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1855 AINPUT_SOURCE_MOUSE)
1856 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1857 .x(900)
1858 .y(400))
1859 .build()));
1860 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1861 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1862 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1863 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1864
1865 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001866 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001867 injectMotionEvent(mDispatcher,
1868 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1869 AINPUT_SOURCE_MOUSE)
1870 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1871 .x(300)
1872 .y(400))
1873 .build()));
1874 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1875 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1876 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1877 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1878 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1879 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1880
1881 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001882 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001883 injectMotionEvent(mDispatcher,
1884 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1885 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1886 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1887 .x(300)
1888 .y(400))
1889 .build()));
1890 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1891
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_BUTTON_PRESS,
1895 AINPUT_SOURCE_MOUSE)
1896 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1897 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1898 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1899 .x(300)
1900 .y(400))
1901 .build()));
1902 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1903 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1904
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001905 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001906 injectMotionEvent(mDispatcher,
1907 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1908 AINPUT_SOURCE_MOUSE)
1909 .buttonState(0)
1910 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1911 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1912 .x(300)
1913 .y(400))
1914 .build()));
1915 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1916 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1917
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001918 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001919 injectMotionEvent(mDispatcher,
1920 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1921 .buttonState(0)
1922 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1923 .x(300)
1924 .y(400))
1925 .build()));
1926 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1927
1928 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001929 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001930 injectMotionEvent(mDispatcher,
1931 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1932 AINPUT_SOURCE_MOUSE)
1933 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1934 .x(900)
1935 .y(400))
1936 .build()));
1937 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1938 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1939 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1940 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1941 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1942 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1943}
1944
1945// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1946// directly in this test.
1947TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001948 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001949 sp<FakeWindowHandle> window =
1950 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1951 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001952 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001953
1954 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1955
1956 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1957
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001958 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001959 injectMotionEvent(mDispatcher,
1960 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1961 AINPUT_SOURCE_MOUSE)
1962 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1963 .x(300)
1964 .y(400))
1965 .build()));
1966 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1967 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1968
1969 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001970 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001971 injectMotionEvent(mDispatcher,
1972 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1973 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1974 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1975 .x(300)
1976 .y(400))
1977 .build()));
1978 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1979
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_BUTTON_PRESS,
1983 AINPUT_SOURCE_MOUSE)
1984 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1985 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1986 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1987 .x(300)
1988 .y(400))
1989 .build()));
1990 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1991 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1992
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001993 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001994 injectMotionEvent(mDispatcher,
1995 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1996 AINPUT_SOURCE_MOUSE)
1997 .buttonState(0)
1998 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1999 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2000 .x(300)
2001 .y(400))
2002 .build()));
2003 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2004 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2005
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002006 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002007 injectMotionEvent(mDispatcher,
2008 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2009 .buttonState(0)
2010 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2011 .x(300)
2012 .y(400))
2013 .build()));
2014 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
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_HOVER_EXIT,
2019 AINPUT_SOURCE_MOUSE)
2020 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2021 .x(300)
2022 .y(400))
2023 .build()));
2024 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2025 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2026}
2027
Garfield Tan00f511d2019-06-12 16:55:40 -07002028TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002029 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002030
2031 sp<FakeWindowHandle> windowLeft =
2032 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2033 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002034 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002035 sp<FakeWindowHandle> windowRight =
2036 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2037 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05002038 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002039
2040 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2041
Arthur Hung72d8dc32020-03-28 00:48:39 +00002042 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002043
2044 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2045 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002046 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002047 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002048 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002049 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002050 windowRight->assertNoEvents();
2051}
2052
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002053TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002054 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002055 sp<FakeWindowHandle> window =
2056 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002057 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002058
Arthur Hung72d8dc32020-03-28 00:48:39 +00002059 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002060 setFocusedWindow(window);
2061
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002062 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002063
2064 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2065 mDispatcher->notifyKey(&keyArgs);
2066
2067 // Window should receive key down event.
2068 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2069
2070 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2071 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002072 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002073 mDispatcher->notifyDeviceReset(&args);
2074 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2075 AKEY_EVENT_FLAG_CANCELED);
2076}
2077
2078TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002079 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002080 sp<FakeWindowHandle> window =
2081 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2082
Arthur Hung72d8dc32020-03-28 00:48:39 +00002083 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002084
2085 NotifyMotionArgs motionArgs =
2086 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2087 ADISPLAY_ID_DEFAULT);
2088 mDispatcher->notifyMotion(&motionArgs);
2089
2090 // Window should receive motion down event.
2091 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2092
2093 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2094 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002095 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002096 mDispatcher->notifyDeviceReset(&args);
2097 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2098 0 /*expectedFlags*/);
2099}
2100
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002101/**
2102 * Ensure the correct coordinate spaces are used by InputDispatcher.
2103 *
2104 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2105 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2106 * space.
2107 */
2108class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2109public:
2110 void SetUp() override {
2111 InputDispatcherTest::SetUp();
2112 mDisplayInfos.clear();
2113 mWindowInfos.clear();
2114 }
2115
2116 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2117 gui::DisplayInfo info;
2118 info.displayId = displayId;
2119 info.transform = transform;
2120 mDisplayInfos.push_back(std::move(info));
2121 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2122 }
2123
2124 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2125 mWindowInfos.push_back(*windowHandle->getInfo());
2126 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2127 }
2128
2129 // Set up a test scenario where the display has a scaled projection and there are two windows
2130 // on the display.
2131 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2132 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2133 // respectively.
2134 ui::Transform displayTransform;
2135 displayTransform.set(2, 0, 0, 4);
2136 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2137
2138 std::shared_ptr<FakeApplicationHandle> application =
2139 std::make_shared<FakeApplicationHandle>();
2140
2141 // Add two windows to the display. Their frames are represented in the display space.
2142 sp<FakeWindowHandle> firstWindow =
2143 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2144 firstWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2145 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2146 addWindow(firstWindow);
2147
2148 sp<FakeWindowHandle> secondWindow =
2149 new FakeWindowHandle(application, mDispatcher, "Second Window",
2150 ADISPLAY_ID_DEFAULT);
2151 secondWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2152 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2153 addWindow(secondWindow);
2154 return {std::move(firstWindow), std::move(secondWindow)};
2155 }
2156
2157private:
2158 std::vector<gui::DisplayInfo> mDisplayInfos;
2159 std::vector<gui::WindowInfo> mWindowInfos;
2160};
2161
2162TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2163 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2164 // Send down to the first window. The point is represented in the display space. The point is
2165 // selected so that if the hit test was done with the transform applied to it, then it would
2166 // end up in the incorrect window.
2167 NotifyMotionArgs downMotionArgs =
2168 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2169 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2170 mDispatcher->notifyMotion(&downMotionArgs);
2171
2172 firstWindow->consumeMotionDown();
2173 secondWindow->assertNoEvents();
2174}
2175
2176// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2177// the event should be treated as being in the logical display space.
2178TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2179 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2180 // Send down to the first window. The point is represented in the logical display space. The
2181 // point is selected so that if the hit test was done in logical display space, then it would
2182 // end up in the incorrect window.
2183 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2184 PointF{75 * 2, 55 * 4});
2185
2186 firstWindow->consumeMotionDown();
2187 secondWindow->assertNoEvents();
2188}
2189
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002190// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2191// event should be treated as being in the logical display space.
2192TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2193 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2194
2195 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2196 ui::Transform injectedEventTransform;
2197 injectedEventTransform.set(matrix);
2198 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2199 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2200
2201 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2202 .displayId(ADISPLAY_ID_DEFAULT)
2203 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2204 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2205 .x(untransformedPoint.x)
2206 .y(untransformedPoint.y))
2207 .build();
2208 event.transform(matrix);
2209
2210 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2211 InputEventInjectionSync::WAIT_FOR_RESULT);
2212
2213 firstWindow->consumeMotionDown();
2214 secondWindow->assertNoEvents();
2215}
2216
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002217TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2218 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2219
2220 // Send down to the second window.
2221 NotifyMotionArgs downMotionArgs =
2222 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2223 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2224 mDispatcher->notifyMotion(&downMotionArgs);
2225
2226 firstWindow->assertNoEvents();
2227 const MotionEvent* event = secondWindow->consumeMotion();
2228 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2229
2230 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2231 EXPECT_EQ(300, event->getRawX(0));
2232 EXPECT_EQ(880, event->getRawY(0));
2233
2234 // Ensure that the x and y values are in the window's coordinate space.
2235 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2236 // the logical display space. This will be the origin of the window space.
2237 EXPECT_EQ(100, event->getX(0));
2238 EXPECT_EQ(80, event->getY(0));
2239}
2240
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002241using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2242 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002243
2244class TransferTouchFixture : public InputDispatcherTest,
2245 public ::testing::WithParamInterface<TransferFunction> {};
2246
2247TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002248 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002249
2250 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002251 sp<FakeWindowHandle> firstWindow =
2252 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2253 sp<FakeWindowHandle> secondWindow =
2254 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002255
2256 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002257 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002258
2259 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002260 NotifyMotionArgs downMotionArgs =
2261 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2262 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002263 mDispatcher->notifyMotion(&downMotionArgs);
2264 // Only the first window should get the down event
2265 firstWindow->consumeMotionDown();
2266 secondWindow->assertNoEvents();
2267
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002268 // Transfer touch to the second window
2269 TransferFunction f = GetParam();
2270 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2271 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002272 // The first window gets cancel and the second gets down
2273 firstWindow->consumeMotionCancel();
2274 secondWindow->consumeMotionDown();
2275
2276 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002277 NotifyMotionArgs upMotionArgs =
2278 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2279 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002280 mDispatcher->notifyMotion(&upMotionArgs);
2281 // The first window gets no events and the second gets up
2282 firstWindow->assertNoEvents();
2283 secondWindow->consumeMotionUp();
2284}
2285
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002286TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002287 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002288
2289 PointF touchPoint = {10, 10};
2290
2291 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002292 sp<FakeWindowHandle> firstWindow =
2293 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2294 sp<FakeWindowHandle> secondWindow =
2295 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002296
2297 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002298 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002299
2300 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002301 NotifyMotionArgs downMotionArgs =
2302 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2303 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002304 mDispatcher->notifyMotion(&downMotionArgs);
2305 // Only the first window should get the down event
2306 firstWindow->consumeMotionDown();
2307 secondWindow->assertNoEvents();
2308
2309 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002310 NotifyMotionArgs pointerDownMotionArgs =
2311 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2312 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2313 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2314 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002315 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2316 // Only the first window should get the pointer down event
2317 firstWindow->consumeMotionPointerDown(1);
2318 secondWindow->assertNoEvents();
2319
2320 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002321 TransferFunction f = GetParam();
2322 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2323 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002324 // The first window gets cancel and the second gets down and pointer down
2325 firstWindow->consumeMotionCancel();
2326 secondWindow->consumeMotionDown();
2327 secondWindow->consumeMotionPointerDown(1);
2328
2329 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002330 NotifyMotionArgs pointerUpMotionArgs =
2331 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2332 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2333 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2334 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002335 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2336 // The first window gets nothing and the second gets pointer up
2337 firstWindow->assertNoEvents();
2338 secondWindow->consumeMotionPointerUp(1);
2339
2340 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002341 NotifyMotionArgs upMotionArgs =
2342 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2343 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002344 mDispatcher->notifyMotion(&upMotionArgs);
2345 // The first window gets nothing and the second gets up
2346 firstWindow->assertNoEvents();
2347 secondWindow->consumeMotionUp();
2348}
2349
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002350// For the cases of single pointer touch and two pointers non-split touch, the api's
2351// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2352// for the case where there are multiple pointers split across several windows.
2353INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2354 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002355 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2356 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002357 return dispatcher->transferTouch(destChannelToken);
2358 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002359 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2360 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002361 return dispatcher->transferTouchFocus(from, to,
2362 false /*isDragAndDrop*/);
2363 }));
2364
Svet Ganov5d3bc372020-01-26 23:11:07 -08002365TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002366 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002367
2368 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002369 sp<FakeWindowHandle> firstWindow =
2370 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002371 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002372 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002373
2374 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002375 sp<FakeWindowHandle> secondWindow =
2376 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002377 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002378 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002379
2380 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002381 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002382
2383 PointF pointInFirst = {300, 200};
2384 PointF pointInSecond = {300, 600};
2385
2386 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002387 NotifyMotionArgs firstDownMotionArgs =
2388 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2389 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002390 mDispatcher->notifyMotion(&firstDownMotionArgs);
2391 // Only the first window should get the down event
2392 firstWindow->consumeMotionDown();
2393 secondWindow->assertNoEvents();
2394
2395 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002396 NotifyMotionArgs secondDownMotionArgs =
2397 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2398 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2399 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2400 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002401 mDispatcher->notifyMotion(&secondDownMotionArgs);
2402 // The first window gets a move and the second a down
2403 firstWindow->consumeMotionMove();
2404 secondWindow->consumeMotionDown();
2405
2406 // Transfer touch focus to the second window
2407 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2408 // The first window gets cancel and the new gets pointer down (it already saw down)
2409 firstWindow->consumeMotionCancel();
2410 secondWindow->consumeMotionPointerDown(1);
2411
2412 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002413 NotifyMotionArgs pointerUpMotionArgs =
2414 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2415 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2416 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2417 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002418 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2419 // The first window gets nothing and the second gets pointer up
2420 firstWindow->assertNoEvents();
2421 secondWindow->consumeMotionPointerUp(1);
2422
2423 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002424 NotifyMotionArgs upMotionArgs =
2425 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2426 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002427 mDispatcher->notifyMotion(&upMotionArgs);
2428 // The first window gets nothing and the second gets up
2429 firstWindow->assertNoEvents();
2430 secondWindow->consumeMotionUp();
2431}
2432
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002433// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2434// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2435// touch is not supported, so the touch should continue on those windows and the transferred-to
2436// window should get nothing.
2437TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2438 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2439
2440 // Create a non touch modal window that supports split touch
2441 sp<FakeWindowHandle> firstWindow =
2442 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2443 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002444 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002445
2446 // Create a non touch modal window that supports split touch
2447 sp<FakeWindowHandle> secondWindow =
2448 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2449 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002450 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002451
2452 // Add the windows to the dispatcher
2453 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2454
2455 PointF pointInFirst = {300, 200};
2456 PointF pointInSecond = {300, 600};
2457
2458 // Send down to the first window
2459 NotifyMotionArgs firstDownMotionArgs =
2460 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2461 ADISPLAY_ID_DEFAULT, {pointInFirst});
2462 mDispatcher->notifyMotion(&firstDownMotionArgs);
2463 // Only the first window should get the down event
2464 firstWindow->consumeMotionDown();
2465 secondWindow->assertNoEvents();
2466
2467 // Send down to the second window
2468 NotifyMotionArgs secondDownMotionArgs =
2469 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2470 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2471 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2472 {pointInFirst, pointInSecond});
2473 mDispatcher->notifyMotion(&secondDownMotionArgs);
2474 // The first window gets a move and the second a down
2475 firstWindow->consumeMotionMove();
2476 secondWindow->consumeMotionDown();
2477
2478 // Transfer touch focus to the second window
2479 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2480 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2481 ASSERT_FALSE(transferred);
2482 firstWindow->assertNoEvents();
2483 secondWindow->assertNoEvents();
2484
2485 // The rest of the dispatch should proceed as normal
2486 // Send pointer up to the second window
2487 NotifyMotionArgs pointerUpMotionArgs =
2488 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2489 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2490 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2491 {pointInFirst, pointInSecond});
2492 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2493 // The first window gets MOVE and the second gets pointer up
2494 firstWindow->consumeMotionMove();
2495 secondWindow->consumeMotionUp();
2496
2497 // Send up event to the first window
2498 NotifyMotionArgs upMotionArgs =
2499 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2500 ADISPLAY_ID_DEFAULT);
2501 mDispatcher->notifyMotion(&upMotionArgs);
2502 // The first window gets nothing and the second gets up
2503 firstWindow->consumeMotionUp();
2504 secondWindow->assertNoEvents();
2505}
2506
Arthur Hungabbb9d82021-09-01 14:52:30 +00002507// This case will create two windows and one mirrored window on the default display and mirror
2508// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2509// the windows info of second display before default display.
2510TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2511 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2512 sp<FakeWindowHandle> firstWindowInPrimary =
2513 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2514 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2515 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2516 sp<FakeWindowHandle> secondWindowInPrimary =
2517 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2518 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2519 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2520
2521 sp<FakeWindowHandle> mirrorWindowInPrimary =
2522 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2523 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2524 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2525
2526 sp<FakeWindowHandle> firstWindowInSecondary =
2527 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2528 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2529 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2530
2531 sp<FakeWindowHandle> secondWindowInSecondary =
2532 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2533 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2534 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2535
2536 // Update window info, let it find window handle of second display first.
2537 mDispatcher->setInputWindows(
2538 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2539 {ADISPLAY_ID_DEFAULT,
2540 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2541
2542 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2543 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2544 {50, 50}))
2545 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2546
2547 // Window should receive motion event.
2548 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2549
2550 // Transfer touch focus
2551 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2552 secondWindowInPrimary->getToken()));
2553 // The first window gets cancel.
2554 firstWindowInPrimary->consumeMotionCancel();
2555 secondWindowInPrimary->consumeMotionDown();
2556
2557 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2558 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2559 ADISPLAY_ID_DEFAULT, {150, 50}))
2560 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2561 firstWindowInPrimary->assertNoEvents();
2562 secondWindowInPrimary->consumeMotionMove();
2563
2564 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2565 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2566 {150, 50}))
2567 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2568 firstWindowInPrimary->assertNoEvents();
2569 secondWindowInPrimary->consumeMotionUp();
2570}
2571
2572// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2573// 'transferTouch' api.
2574TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2575 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2576 sp<FakeWindowHandle> firstWindowInPrimary =
2577 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2578 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2579 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2580 sp<FakeWindowHandle> secondWindowInPrimary =
2581 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2582 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2583 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2584
2585 sp<FakeWindowHandle> mirrorWindowInPrimary =
2586 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2587 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2588 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2589
2590 sp<FakeWindowHandle> firstWindowInSecondary =
2591 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2592 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2593 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2594
2595 sp<FakeWindowHandle> secondWindowInSecondary =
2596 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2597 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2598 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2599
2600 // Update window info, let it find window handle of second display first.
2601 mDispatcher->setInputWindows(
2602 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2603 {ADISPLAY_ID_DEFAULT,
2604 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2605
2606 // Touch on second display.
2607 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2608 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2609 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2610
2611 // Window should receive motion event.
2612 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2613
2614 // Transfer touch focus
2615 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2616
2617 // The first window gets cancel.
2618 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2619 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2620
2621 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2622 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2623 SECOND_DISPLAY_ID, {150, 50}))
2624 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2625 firstWindowInPrimary->assertNoEvents();
2626 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2627
2628 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2629 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2630 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2631 firstWindowInPrimary->assertNoEvents();
2632 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2633}
2634
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002635TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002636 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002637 sp<FakeWindowHandle> window =
2638 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2639
Vishnu Nair47074b82020-08-14 11:54:47 -07002640 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002641 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002642 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002643
2644 window->consumeFocusEvent(true);
2645
2646 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2647 mDispatcher->notifyKey(&keyArgs);
2648
2649 // Window should receive key down event.
2650 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2651}
2652
2653TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002654 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002655 sp<FakeWindowHandle> window =
2656 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2657
Arthur Hung72d8dc32020-03-28 00:48:39 +00002658 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002659
2660 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2661 mDispatcher->notifyKey(&keyArgs);
2662 mDispatcher->waitForIdle();
2663
2664 window->assertNoEvents();
2665}
2666
2667// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2668TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002669 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002670 sp<FakeWindowHandle> window =
2671 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2672
Arthur Hung72d8dc32020-03-28 00:48:39 +00002673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002674
2675 // Send key
2676 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2677 mDispatcher->notifyKey(&keyArgs);
2678 // Send motion
2679 NotifyMotionArgs motionArgs =
2680 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2681 ADISPLAY_ID_DEFAULT);
2682 mDispatcher->notifyMotion(&motionArgs);
2683
2684 // Window should receive only the motion event
2685 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2686 window->assertNoEvents(); // Key event or focus event will not be received
2687}
2688
arthurhungea3f4fc2020-12-21 23:18:53 +08002689TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2690 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2691
2692 // Create first non touch modal window that supports split touch
2693 sp<FakeWindowHandle> firstWindow =
2694 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2695 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002696 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002697
2698 // Create second non touch modal window that supports split touch
2699 sp<FakeWindowHandle> secondWindow =
2700 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2701 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002702 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002703
2704 // Add the windows to the dispatcher
2705 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2706
2707 PointF pointInFirst = {300, 200};
2708 PointF pointInSecond = {300, 600};
2709
2710 // Send down to the first window
2711 NotifyMotionArgs firstDownMotionArgs =
2712 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2713 ADISPLAY_ID_DEFAULT, {pointInFirst});
2714 mDispatcher->notifyMotion(&firstDownMotionArgs);
2715 // Only the first window should get the down event
2716 firstWindow->consumeMotionDown();
2717 secondWindow->assertNoEvents();
2718
2719 // Send down to the second window
2720 NotifyMotionArgs secondDownMotionArgs =
2721 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2722 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2723 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2724 {pointInFirst, pointInSecond});
2725 mDispatcher->notifyMotion(&secondDownMotionArgs);
2726 // The first window gets a move and the second a down
2727 firstWindow->consumeMotionMove();
2728 secondWindow->consumeMotionDown();
2729
2730 // Send pointer cancel to the second window
2731 NotifyMotionArgs pointerUpMotionArgs =
2732 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2733 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2734 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2735 {pointInFirst, pointInSecond});
2736 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2737 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2738 // The first window gets move and the second gets cancel.
2739 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2740 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2741
2742 // Send up event.
2743 NotifyMotionArgs upMotionArgs =
2744 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2745 ADISPLAY_ID_DEFAULT);
2746 mDispatcher->notifyMotion(&upMotionArgs);
2747 // The first window gets up and the second gets nothing.
2748 firstWindow->consumeMotionUp();
2749 secondWindow->assertNoEvents();
2750}
2751
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002752TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2753 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2754
2755 sp<FakeWindowHandle> window =
2756 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2757 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2758 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2759 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2760 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2761
2762 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2763 window->assertNoEvents();
2764 mDispatcher->waitForIdle();
2765}
2766
chaviwd1c23182019-12-20 18:44:56 -08002767class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002768public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002769 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
chaviwd1c23182019-12-20 18:44:56 -08002770 int32_t displayId, bool isGestureMonitor = false) {
Garfield Tan15601662020-09-22 15:32:38 -07002771 base::Result<std::unique_ptr<InputChannel>> channel =
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +00002772 dispatcher->createInputMonitor(displayId, isGestureMonitor, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002773 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002774 }
2775
chaviwd1c23182019-12-20 18:44:56 -08002776 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2777
2778 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2779 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2780 expectedDisplayId, expectedFlags);
2781 }
2782
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002783 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2784
2785 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2786
chaviwd1c23182019-12-20 18:44:56 -08002787 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2788 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2789 expectedDisplayId, expectedFlags);
2790 }
2791
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002792 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2793 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2794 expectedDisplayId, expectedFlags);
2795 }
2796
chaviwd1c23182019-12-20 18:44:56 -08002797 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2798 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2799 expectedDisplayId, expectedFlags);
2800 }
2801
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002802 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2803 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2804 expectedDisplayId, expectedFlags);
2805 }
2806
Arthur Hungfbfa5722021-11-16 02:45:54 +00002807 void consumeMotionPointerDown(int32_t pointerIdx) {
2808 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2809 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2810 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2811 0 /*expectedFlags*/);
2812 }
2813
Evan Rosky84f07f02021-04-16 10:42:42 -07002814 MotionEvent* consumeMotion() {
2815 InputEvent* event = mInputReceiver->consume();
2816 if (!event) {
2817 ADD_FAILURE() << "No event was produced";
2818 return nullptr;
2819 }
2820 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2821 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2822 return nullptr;
2823 }
2824 return static_cast<MotionEvent*>(event);
2825 }
2826
chaviwd1c23182019-12-20 18:44:56 -08002827 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2828
2829private:
2830 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002831};
2832
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002833/**
2834 * Two entities that receive touch: A window, and a global monitor.
2835 * The touch goes to the window, and then the window disappears.
2836 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2837 * for the monitor, as well.
2838 * 1. foregroundWindow
2839 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2840 */
2841TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_GlobalMonitorTouchIsCanceled) {
2842 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2843 sp<FakeWindowHandle> window =
2844 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2845
2846 FakeMonitorReceiver monitor =
2847 FakeMonitorReceiver(mDispatcher, "GlobalMonitor", ADISPLAY_ID_DEFAULT,
2848 false /*isGestureMonitor*/);
2849
2850 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2851 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2852 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2853 {100, 200}))
2854 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2855
2856 // Both the foreground window and the global monitor should receive the touch down
2857 window->consumeMotionDown();
2858 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2859
2860 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2861 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2862 ADISPLAY_ID_DEFAULT, {110, 200}))
2863 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2864
2865 window->consumeMotionMove();
2866 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2867
2868 // Now the foreground window goes away
2869 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2870 window->consumeMotionCancel();
2871 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2872
2873 // If more events come in, there will be no more foreground window to send them to. This will
2874 // cause a cancel for the monitor, as well.
2875 ASSERT_EQ(InputEventInjectionResult::FAILED,
2876 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2877 ADISPLAY_ID_DEFAULT, {120, 200}))
2878 << "Injection should fail because the window was removed";
2879 window->assertNoEvents();
2880 // Global monitor now gets the cancel
2881 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2882}
2883
Michael Wright3a240c42019-12-10 20:53:41 +00002884// Tests for gesture monitors
2885TEST_F(InputDispatcherTest, GestureMonitor_ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002886 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002887 sp<FakeWindowHandle> window =
2888 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002889 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002890
chaviwd1c23182019-12-20 18:44:56 -08002891 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2892 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002893
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002894 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002895 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002896 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002897 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002898 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002899}
2900
2901TEST_F(InputDispatcherTest, GestureMonitor_DoesNotReceiveKeyEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002902 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002903 sp<FakeWindowHandle> window =
2904 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2905
2906 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002907 window->setFocusable(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002908
Arthur Hung72d8dc32020-03-28 00:48:39 +00002909 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002910 setFocusedWindow(window);
2911
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002912 window->consumeFocusEvent(true);
Michael Wright3a240c42019-12-10 20:53:41 +00002913
chaviwd1c23182019-12-20 18:44:56 -08002914 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2915 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002916
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002917 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
2918 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002919 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002920 monitor.assertNoEvents();
Michael Wright3a240c42019-12-10 20:53:41 +00002921}
2922
2923TEST_F(InputDispatcherTest, GestureMonitor_CanPilferAfterWindowIsRemovedMidStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002924 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002925 sp<FakeWindowHandle> window =
2926 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002927 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002928
chaviwd1c23182019-12-20 18:44:56 -08002929 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2930 true /*isGestureMonitor*/);
Michael Wright3a240c42019-12-10 20:53:41 +00002931
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002932 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002933 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002934 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002935 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002936 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002937
2938 window->releaseChannel();
2939
chaviwd1c23182019-12-20 18:44:56 -08002940 mDispatcher->pilferPointers(monitor.getToken());
Michael Wright3a240c42019-12-10 20:53:41 +00002941
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002942 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002943 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002944 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002945 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002946}
2947
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002948TEST_F(InputDispatcherTest, UnresponsiveGestureMonitor_GetsAnr) {
2949 FakeMonitorReceiver monitor =
2950 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
2951 true /*isGestureMonitor*/);
2952
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002953 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002954 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT));
2955 std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
2956 ASSERT_TRUE(consumeSeq);
2957
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002958 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(DISPATCHING_TIMEOUT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002959 monitor.finishEvent(*consumeSeq);
2960 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00002961 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002962}
2963
Evan Rosky84f07f02021-04-16 10:42:42 -07002964// Tests for gesture monitors
2965TEST_F(InputDispatcherTest, GestureMonitor_NoWindowTransform) {
2966 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2967 sp<FakeWindowHandle> window =
2968 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2969 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2970 window->setWindowOffset(20, 40);
2971 window->setWindowTransform(0, 1, -1, 0);
2972
2973 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2974 true /*isGestureMonitor*/);
2975
2976 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2977 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2978 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2979 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2980 MotionEvent* event = monitor.consumeMotion();
2981 // Even though window has transform, gesture monitor must not.
2982 ASSERT_EQ(ui::Transform(), event->getTransform());
2983}
2984
Arthur Hungb3307ee2021-10-14 10:57:37 +00002985TEST_F(InputDispatcherTest, GestureMonitor_NoWindow) {
2986 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2987 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
2988 true /*isGestureMonitor*/);
2989
2990 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2991 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2992 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2993 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2994}
2995
chaviw81e2bb92019-12-18 15:03:51 -08002996TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002997 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002998 sp<FakeWindowHandle> window =
2999 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3000
Arthur Hung72d8dc32020-03-28 00:48:39 +00003001 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003002
3003 NotifyMotionArgs motionArgs =
3004 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3005 ADISPLAY_ID_DEFAULT);
3006
3007 mDispatcher->notifyMotion(&motionArgs);
3008 // Window should receive motion down event.
3009 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3010
3011 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003012 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003013 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3014 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3015 motionArgs.pointerCoords[0].getX() - 10);
3016
3017 mDispatcher->notifyMotion(&motionArgs);
3018 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3019 0 /*expectedFlags*/);
3020}
3021
Arthur Hungfbfa5722021-11-16 02:45:54 +00003022TEST_F(InputDispatcherTest, GestureMonitor_SplitIfNoWindowTouched) {
3023 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
3024 true /*isGestureMonitor*/);
3025
3026 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3027 // Create a non touch modal window that supports split touch
3028 sp<FakeWindowHandle> window =
3029 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3030 window->setFrame(Rect(0, 0, 100, 100));
3031 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
3032 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3033
3034 // First finger down, no window touched.
3035 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3036 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3037 {100, 200}))
3038 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3039 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3040 window->assertNoEvents();
3041
3042 // Second finger down on window, the window should receive touch down.
3043 const MotionEvent secondFingerDownEvent =
3044 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
3045 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
3046 AINPUT_SOURCE_TOUCHSCREEN)
3047 .displayId(ADISPLAY_ID_DEFAULT)
3048 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3049 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3050 .x(100)
3051 .y(200))
3052 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3053 .build();
3054 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3055 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
3056 InputEventInjectionSync::WAIT_FOR_RESULT))
3057 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3058
3059 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3060 monitor.consumeMotionPointerDown(1 /* pointerIndex */);
3061}
3062
3063TEST_F(InputDispatcherTest, GestureMonitor_NoSplitAfterPilfer) {
3064 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
3065 true /*isGestureMonitor*/);
3066
3067 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3068 // Create a non touch modal window that supports split touch
3069 sp<FakeWindowHandle> window =
3070 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3071 window->setFrame(Rect(0, 0, 100, 100));
3072 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
3073 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3074
3075 // First finger down, no window touched.
3076 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3077 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
3078 {100, 200}))
3079 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3080 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3081 window->assertNoEvents();
3082
3083 // Gesture monitor pilfer the pointers.
3084 mDispatcher->pilferPointers(monitor.getToken());
3085
3086 // Second finger down on window, the window should not receive touch down.
3087 const MotionEvent secondFingerDownEvent =
3088 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
3089 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
3090 AINPUT_SOURCE_TOUCHSCREEN)
3091 .displayId(ADISPLAY_ID_DEFAULT)
3092 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
3093 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
3094 .x(100)
3095 .y(200))
3096 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
3097 .build();
3098 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3099 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
3100 InputEventInjectionSync::WAIT_FOR_RESULT))
3101 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3102
3103 window->assertNoEvents();
3104 monitor.consumeMotionPointerDown(1 /* pointerIndex */);
3105}
3106
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003107/**
3108 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3109 * the device default right away. In the test scenario, we check both the default value,
3110 * and the action of enabling / disabling.
3111 */
3112TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003113 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003114 sp<FakeWindowHandle> window =
3115 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3116
3117 // Set focused application.
3118 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003119 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003120
3121 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003122 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003123 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003124 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3125
3126 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003127 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003128 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003129 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3130
3131 SCOPED_TRACE("Disable touch mode");
3132 mDispatcher->setInTouchMode(false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003133 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003134 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003135 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003136 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003137 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3138
3139 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003140 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003141 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003142 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3143
3144 SCOPED_TRACE("Enable touch mode again");
3145 mDispatcher->setInTouchMode(true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003146 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003147 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003148 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003149 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003150 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3151
3152 window->assertNoEvents();
3153}
3154
Gang Wange9087892020-01-07 12:17:14 -05003155TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003156 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003157 sp<FakeWindowHandle> window =
3158 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3159
3160 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003161 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003162
Arthur Hung72d8dc32020-03-28 00:48:39 +00003163 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003164 setFocusedWindow(window);
3165
Gang Wange9087892020-01-07 12:17:14 -05003166 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3167
3168 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3169 mDispatcher->notifyKey(&keyArgs);
3170
3171 InputEvent* event = window->consume();
3172 ASSERT_NE(event, nullptr);
3173
3174 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3175 ASSERT_NE(verified, nullptr);
3176 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3177
3178 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3179 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3180 ASSERT_EQ(keyArgs.source, verified->source);
3181 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3182
3183 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3184
3185 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003186 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003187 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003188 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3189 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3190 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3191 ASSERT_EQ(0, verifiedKey.repeatCount);
3192}
3193
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003194TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003195 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003196 sp<FakeWindowHandle> window =
3197 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3198
3199 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3200
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003201 ui::Transform transform;
3202 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3203
3204 gui::DisplayInfo displayInfo;
3205 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3206 displayInfo.transform = transform;
3207
3208 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003209
3210 NotifyMotionArgs motionArgs =
3211 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3212 ADISPLAY_ID_DEFAULT);
3213 mDispatcher->notifyMotion(&motionArgs);
3214
3215 InputEvent* event = window->consume();
3216 ASSERT_NE(event, nullptr);
3217
3218 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3219 ASSERT_NE(verified, nullptr);
3220 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3221
3222 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3223 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3224 EXPECT_EQ(motionArgs.source, verified->source);
3225 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3226
3227 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3228
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003229 const vec2 rawXY =
3230 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3231 motionArgs.pointerCoords[0].getXYValue());
3232 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3233 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003234 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003235 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003236 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003237 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3238 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3239}
3240
chaviw09c8d2d2020-08-24 15:48:26 -07003241/**
3242 * Ensure that separate calls to sign the same data are generating the same key.
3243 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3244 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3245 * tests.
3246 */
3247TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3248 KeyEvent event = getTestKeyEvent();
3249 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3250
3251 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3252 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3253 ASSERT_EQ(hmac1, hmac2);
3254}
3255
3256/**
3257 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3258 */
3259TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3260 KeyEvent event = getTestKeyEvent();
3261 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3262 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3263
3264 verifiedEvent.deviceId += 1;
3265 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3266
3267 verifiedEvent.source += 1;
3268 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3269
3270 verifiedEvent.eventTimeNanos += 1;
3271 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3272
3273 verifiedEvent.displayId += 1;
3274 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3275
3276 verifiedEvent.action += 1;
3277 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3278
3279 verifiedEvent.downTimeNanos += 1;
3280 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3281
3282 verifiedEvent.flags += 1;
3283 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3284
3285 verifiedEvent.keyCode += 1;
3286 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3287
3288 verifiedEvent.scanCode += 1;
3289 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3290
3291 verifiedEvent.metaState += 1;
3292 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3293
3294 verifiedEvent.repeatCount += 1;
3295 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3296}
3297
Vishnu Nair958da932020-08-21 17:12:37 -07003298TEST_F(InputDispatcherTest, SetFocusedWindow) {
3299 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3300 sp<FakeWindowHandle> windowTop =
3301 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3302 sp<FakeWindowHandle> windowSecond =
3303 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3304 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3305
3306 // Top window is also focusable but is not granted focus.
3307 windowTop->setFocusable(true);
3308 windowSecond->setFocusable(true);
3309 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3310 setFocusedWindow(windowSecond);
3311
3312 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003313 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3314 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003315
3316 // Focused window should receive event.
3317 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3318 windowTop->assertNoEvents();
3319}
3320
3321TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3322 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3323 sp<FakeWindowHandle> window =
3324 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3325 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3326
3327 window->setFocusable(true);
3328 // Release channel for window is no longer valid.
3329 window->releaseChannel();
3330 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3331 setFocusedWindow(window);
3332
3333 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003334 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3335 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003336
3337 // window channel is invalid, so it should not receive any input event.
3338 window->assertNoEvents();
3339}
3340
3341TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3342 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3343 sp<FakeWindowHandle> window =
3344 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3345 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3346
3347 // Window is not focusable.
3348 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3349 setFocusedWindow(window);
3350
3351 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003352 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3353 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003354
3355 // window is invalid, so it should not receive any input event.
3356 window->assertNoEvents();
3357}
3358
3359TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3360 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3361 sp<FakeWindowHandle> windowTop =
3362 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3363 sp<FakeWindowHandle> windowSecond =
3364 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3365 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3366
3367 windowTop->setFocusable(true);
3368 windowSecond->setFocusable(true);
3369 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3370 setFocusedWindow(windowTop);
3371 windowTop->consumeFocusEvent(true);
3372
3373 setFocusedWindow(windowSecond, windowTop);
3374 windowSecond->consumeFocusEvent(true);
3375 windowTop->consumeFocusEvent(false);
3376
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003377 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3378 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003379
3380 // Focused window should receive event.
3381 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3382}
3383
3384TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3385 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3386 sp<FakeWindowHandle> windowTop =
3387 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3388 sp<FakeWindowHandle> windowSecond =
3389 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3390 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3391
3392 windowTop->setFocusable(true);
3393 windowSecond->setFocusable(true);
3394 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3395 setFocusedWindow(windowSecond, windowTop);
3396
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003397 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3398 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003399
3400 // Event should be dropped.
3401 windowTop->assertNoEvents();
3402 windowSecond->assertNoEvents();
3403}
3404
3405TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3406 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3407 sp<FakeWindowHandle> window =
3408 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3409 sp<FakeWindowHandle> previousFocusedWindow =
3410 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3411 ADISPLAY_ID_DEFAULT);
3412 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3413
3414 window->setFocusable(true);
3415 previousFocusedWindow->setFocusable(true);
3416 window->setVisible(false);
3417 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3418 setFocusedWindow(previousFocusedWindow);
3419 previousFocusedWindow->consumeFocusEvent(true);
3420
3421 // Requesting focus on invisible window takes focus from currently focused window.
3422 setFocusedWindow(window);
3423 previousFocusedWindow->consumeFocusEvent(false);
3424
3425 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003426 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003427 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003428 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003429
3430 // Window does not get focus event or key down.
3431 window->assertNoEvents();
3432
3433 // Window becomes visible.
3434 window->setVisible(true);
3435 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3436
3437 // Window receives focus event.
3438 window->consumeFocusEvent(true);
3439 // Focused window receives key down.
3440 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3441}
3442
Vishnu Nair599f1412021-06-21 10:39:58 -07003443TEST_F(InputDispatcherTest, DisplayRemoved) {
3444 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3445 sp<FakeWindowHandle> window =
3446 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3447 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3448
3449 // window is granted focus.
3450 window->setFocusable(true);
3451 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3452 setFocusedWindow(window);
3453 window->consumeFocusEvent(true);
3454
3455 // When a display is removed window loses focus.
3456 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3457 window->consumeFocusEvent(false);
3458}
3459
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003460/**
3461 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3462 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3463 * of the 'slipperyEnterWindow'.
3464 *
3465 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3466 * a way so that the touched location is no longer covered by the top window.
3467 *
3468 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3469 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3470 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3471 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3472 * with ACTION_DOWN).
3473 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3474 * window moved itself away from the touched location and had Flag::SLIPPERY.
3475 *
3476 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3477 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3478 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3479 *
3480 * In this test, we ensure that the event received by the bottom window has
3481 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3482 */
3483TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3484 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3485 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3486
3487 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3488 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3489
3490 sp<FakeWindowHandle> slipperyExitWindow =
3491 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003492 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003493 // Make sure this one overlaps the bottom window
3494 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3495 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3496 // one. Windows with the same owner are not considered to be occluding each other.
3497 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3498
3499 sp<FakeWindowHandle> slipperyEnterWindow =
3500 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3501 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3502
3503 mDispatcher->setInputWindows(
3504 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3505
3506 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3507 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3508 ADISPLAY_ID_DEFAULT, {{50, 50}});
3509 mDispatcher->notifyMotion(&args);
3510 slipperyExitWindow->consumeMotionDown();
3511 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3512 mDispatcher->setInputWindows(
3513 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3514
3515 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3516 ADISPLAY_ID_DEFAULT, {{51, 51}});
3517 mDispatcher->notifyMotion(&args);
3518
3519 slipperyExitWindow->consumeMotionCancel();
3520
3521 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3522 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3523}
3524
Garfield Tan1c7bc862020-01-28 13:24:04 -08003525class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3526protected:
3527 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3528 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3529
Chris Yea209fde2020-07-22 13:54:51 -07003530 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003531 sp<FakeWindowHandle> mWindow;
3532
3533 virtual void SetUp() override {
3534 mFakePolicy = new FakeInputDispatcherPolicy();
3535 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003536 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003537 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3538 ASSERT_EQ(OK, mDispatcher->start());
3539
3540 setUpWindow();
3541 }
3542
3543 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003544 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003545 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3546
Vishnu Nair47074b82020-08-14 11:54:47 -07003547 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003548 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003549 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003550 mWindow->consumeFocusEvent(true);
3551 }
3552
Chris Ye2ad95392020-09-01 13:44:44 -07003553 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003554 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003555 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003556 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3557 mDispatcher->notifyKey(&keyArgs);
3558
3559 // Window should receive key down event.
3560 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3561 }
3562
3563 void expectKeyRepeatOnce(int32_t repeatCount) {
3564 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3565 InputEvent* repeatEvent = mWindow->consume();
3566 ASSERT_NE(nullptr, repeatEvent);
3567
3568 uint32_t eventType = repeatEvent->getType();
3569 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3570
3571 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3572 uint32_t eventAction = repeatKeyEvent->getAction();
3573 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3574 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3575 }
3576
Chris Ye2ad95392020-09-01 13:44:44 -07003577 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003578 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003579 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003580 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3581 mDispatcher->notifyKey(&keyArgs);
3582
3583 // Window should receive key down event.
3584 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3585 0 /*expectedFlags*/);
3586 }
3587};
3588
3589TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003590 sendAndConsumeKeyDown(1 /* deviceId */);
3591 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3592 expectKeyRepeatOnce(repeatCount);
3593 }
3594}
3595
3596TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3597 sendAndConsumeKeyDown(1 /* deviceId */);
3598 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3599 expectKeyRepeatOnce(repeatCount);
3600 }
3601 sendAndConsumeKeyDown(2 /* deviceId */);
3602 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003603 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3604 expectKeyRepeatOnce(repeatCount);
3605 }
3606}
3607
3608TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003609 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003610 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003611 sendAndConsumeKeyUp(1 /* deviceId */);
3612 mWindow->assertNoEvents();
3613}
3614
3615TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3616 sendAndConsumeKeyDown(1 /* deviceId */);
3617 expectKeyRepeatOnce(1 /*repeatCount*/);
3618 sendAndConsumeKeyDown(2 /* deviceId */);
3619 expectKeyRepeatOnce(1 /*repeatCount*/);
3620 // Stale key up from device 1.
3621 sendAndConsumeKeyUp(1 /* deviceId */);
3622 // Device 2 is still down, keep repeating
3623 expectKeyRepeatOnce(2 /*repeatCount*/);
3624 expectKeyRepeatOnce(3 /*repeatCount*/);
3625 // Device 2 key up
3626 sendAndConsumeKeyUp(2 /* deviceId */);
3627 mWindow->assertNoEvents();
3628}
3629
3630TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3631 sendAndConsumeKeyDown(1 /* deviceId */);
3632 expectKeyRepeatOnce(1 /*repeatCount*/);
3633 sendAndConsumeKeyDown(2 /* deviceId */);
3634 expectKeyRepeatOnce(1 /*repeatCount*/);
3635 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3636 sendAndConsumeKeyUp(2 /* deviceId */);
3637 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003638 mWindow->assertNoEvents();
3639}
3640
liushenxiang42232912021-05-21 20:24:09 +08003641TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3642 sendAndConsumeKeyDown(DEVICE_ID);
3643 expectKeyRepeatOnce(1 /*repeatCount*/);
3644 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3645 mDispatcher->notifyDeviceReset(&args);
3646 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3647 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3648 mWindow->assertNoEvents();
3649}
3650
Garfield Tan1c7bc862020-01-28 13:24:04 -08003651TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003652 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003653 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3654 InputEvent* repeatEvent = mWindow->consume();
3655 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3656 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3657 IdGenerator::getSource(repeatEvent->getId()));
3658 }
3659}
3660
3661TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003662 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003663
3664 std::unordered_set<int32_t> idSet;
3665 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3666 InputEvent* repeatEvent = mWindow->consume();
3667 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3668 int32_t id = repeatEvent->getId();
3669 EXPECT_EQ(idSet.end(), idSet.find(id));
3670 idSet.insert(id);
3671 }
3672}
3673
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003674/* Test InputDispatcher for MultiDisplay */
3675class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3676public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003677 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003678 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003679
Chris Yea209fde2020-07-22 13:54:51 -07003680 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003681 windowInPrimary =
3682 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003683
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003684 // Set focus window for primary display, but focused display would be second one.
3685 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003686 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003687 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003688 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003689 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003690
Chris Yea209fde2020-07-22 13:54:51 -07003691 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003692 windowInSecondary =
3693 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003694 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003695 // Set focus display to second one.
3696 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3697 // Set focus window for second display.
3698 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003699 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003700 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003701 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003702 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003703 }
3704
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003705 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003706 InputDispatcherTest::TearDown();
3707
Chris Yea209fde2020-07-22 13:54:51 -07003708 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003709 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003710 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003711 windowInSecondary.clear();
3712 }
3713
3714protected:
Chris Yea209fde2020-07-22 13:54:51 -07003715 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003716 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003717 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003718 sp<FakeWindowHandle> windowInSecondary;
3719};
3720
3721TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3722 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003723 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3724 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3725 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003726 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003727 windowInSecondary->assertNoEvents();
3728
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003729 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003730 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3731 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3732 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003733 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003734 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003735}
3736
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003737TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003738 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003739 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3740 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003741 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003742 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003743 windowInSecondary->assertNoEvents();
3744
3745 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003746 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003747 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003748 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003749 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003750
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003751 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003752 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003753
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003754 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003755 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3756 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003757
3758 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003759 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003760 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003761 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003762 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003763 windowInSecondary->assertNoEvents();
3764}
3765
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003766// Test per-display input monitors for motion event.
3767TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003768 FakeMonitorReceiver monitorInPrimary =
3769 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3770 FakeMonitorReceiver monitorInSecondary =
3771 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003772
3773 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003774 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3775 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3776 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003777 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003778 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003779 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003780 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003781
3782 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003783 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3784 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3785 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003786 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003787 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003788 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003789 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003790
3791 // Test inject a non-pointer motion event.
3792 // If specific a display, it will dispatch to the focused window of particular display,
3793 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003794 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3795 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3796 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003797 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003798 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003799 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003800 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003801}
3802
3803// Test per-display input monitors for key event.
3804TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003805 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003806 FakeMonitorReceiver monitorInPrimary =
3807 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3808 FakeMonitorReceiver monitorInSecondary =
3809 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003810
3811 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003812 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3813 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003814 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003815 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003816 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003817 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003818}
3819
Vishnu Nair958da932020-08-21 17:12:37 -07003820TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3821 sp<FakeWindowHandle> secondWindowInPrimary =
3822 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3823 secondWindowInPrimary->setFocusable(true);
3824 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3825 setFocusedWindow(secondWindowInPrimary);
3826 windowInPrimary->consumeFocusEvent(false);
3827 secondWindowInPrimary->consumeFocusEvent(true);
3828
3829 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003830 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3831 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003832 windowInPrimary->assertNoEvents();
3833 windowInSecondary->assertNoEvents();
3834 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3835}
3836
Arthur Hungdfd528e2021-12-08 13:23:04 +00003837TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3838 FakeMonitorReceiver monitorInPrimary =
3839 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3840 FakeMonitorReceiver monitorInSecondary =
3841 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3842
3843 // Test touch down on primary display.
3844 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3845 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3846 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3847 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3848 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3849
3850 // Test touch down on second display.
3851 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3852 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3853 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3854 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3855 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3856
3857 // Trigger cancel touch.
3858 mDispatcher->cancelCurrentTouch();
3859 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3860 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3861 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3862 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3863
3864 // Test inject a move motion event, no window/monitor should receive the event.
3865 ASSERT_EQ(InputEventInjectionResult::FAILED,
3866 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3867 ADISPLAY_ID_DEFAULT, {110, 200}))
3868 << "Inject motion event should return InputEventInjectionResult::FAILED";
3869 windowInPrimary->assertNoEvents();
3870 monitorInPrimary.assertNoEvents();
3871
3872 ASSERT_EQ(InputEventInjectionResult::FAILED,
3873 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3874 SECOND_DISPLAY_ID, {110, 200}))
3875 << "Inject motion event should return InputEventInjectionResult::FAILED";
3876 windowInSecondary->assertNoEvents();
3877 monitorInSecondary.assertNoEvents();
3878}
3879
Jackal Guof9696682018-10-05 12:23:23 +08003880class InputFilterTest : public InputDispatcherTest {
3881protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003882 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3883 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003884 NotifyMotionArgs motionArgs;
3885
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003886 motionArgs =
3887 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003888 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003889 motionArgs =
3890 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003891 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003892 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003893 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003894 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3895 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003896 } else {
3897 mFakePolicy->assertFilterInputEventWasNotCalled();
3898 }
3899 }
3900
3901 void testNotifyKey(bool expectToBeFiltered) {
3902 NotifyKeyArgs keyArgs;
3903
3904 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3905 mDispatcher->notifyKey(&keyArgs);
3906 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3907 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003908 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003909
3910 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003911 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003912 } else {
3913 mFakePolicy->assertFilterInputEventWasNotCalled();
3914 }
3915 }
3916};
3917
3918// Test InputFilter for MotionEvent
3919TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3920 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3921 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3922 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3923
3924 // Enable InputFilter
3925 mDispatcher->setInputFilterEnabled(true);
3926 // Test touch on both primary and second display, and check if both events are filtered.
3927 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3928 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3929
3930 // Disable InputFilter
3931 mDispatcher->setInputFilterEnabled(false);
3932 // Test touch on both primary and second display, and check if both events aren't filtered.
3933 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3934 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3935}
3936
3937// Test InputFilter for KeyEvent
3938TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3939 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3940 testNotifyKey(/*expectToBeFiltered*/ false);
3941
3942 // Enable InputFilter
3943 mDispatcher->setInputFilterEnabled(true);
3944 // Send a key event, and check if it is filtered.
3945 testNotifyKey(/*expectToBeFiltered*/ true);
3946
3947 // Disable InputFilter
3948 mDispatcher->setInputFilterEnabled(false);
3949 // Send a key event, and check if it isn't filtered.
3950 testNotifyKey(/*expectToBeFiltered*/ false);
3951}
3952
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003953// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3954// logical display coordinate space.
3955TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3956 ui::Transform firstDisplayTransform;
3957 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3958 ui::Transform secondDisplayTransform;
3959 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3960
3961 std::vector<gui::DisplayInfo> displayInfos(2);
3962 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3963 displayInfos[0].transform = firstDisplayTransform;
3964 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3965 displayInfos[1].transform = secondDisplayTransform;
3966
3967 mDispatcher->onWindowInfosChanged({}, displayInfos);
3968
3969 // Enable InputFilter
3970 mDispatcher->setInputFilterEnabled(true);
3971
3972 // Ensure the correct transforms are used for the displays.
3973 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3974 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3975}
3976
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003977class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3978protected:
3979 virtual void SetUp() override {
3980 InputDispatcherTest::SetUp();
3981
3982 /**
3983 * We don't need to enable input filter to test the injected event policy, but we enabled it
3984 * here to make the tests more realistic, since this policy only matters when inputfilter is
3985 * on.
3986 */
3987 mDispatcher->setInputFilterEnabled(true);
3988
3989 std::shared_ptr<InputApplicationHandle> application =
3990 std::make_shared<FakeApplicationHandle>();
3991 mWindow =
3992 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3993
3994 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3995 mWindow->setFocusable(true);
3996 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3997 setFocusedWindow(mWindow);
3998 mWindow->consumeFocusEvent(true);
3999 }
4000
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004001 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4002 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004003 KeyEvent event;
4004
4005 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4006 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
4007 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
4008 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
4009 const int32_t additionalPolicyFlags =
4010 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
4011 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4012 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
4013 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4014 policyFlags | additionalPolicyFlags));
4015
4016 InputEvent* received = mWindow->consume();
4017 ASSERT_NE(nullptr, received);
4018 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004019 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4020 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4021 ASSERT_EQ(flags, keyEvent.getFlags());
4022 }
4023
4024 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4025 int32_t flags) {
4026 MotionEvent event;
4027 PointerProperties pointerProperties[1];
4028 PointerCoords pointerCoords[1];
4029 pointerProperties[0].clear();
4030 pointerProperties[0].id = 0;
4031 pointerCoords[0].clear();
4032 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4033 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4034
4035 ui::Transform identityTransform;
4036 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4037 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4038 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4039 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4040 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004041 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004042 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004043 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4044
4045 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4046 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4047 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
4048 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4049 policyFlags | additionalPolicyFlags));
4050
4051 InputEvent* received = mWindow->consume();
4052 ASSERT_NE(nullptr, received);
4053 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4054 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4055 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4056 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004057 }
4058
4059private:
4060 sp<FakeWindowHandle> mWindow;
4061};
4062
4063TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004064 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4065 // filter. Without it, the event will no different from a regularly injected event, and the
4066 // injected device id will be overwritten.
4067 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4068 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004069}
4070
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004071TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004072 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004073 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4074 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4075}
4076
4077TEST_F(InputFilterInjectionPolicyTest,
4078 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4079 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4080 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4081 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004082}
4083
4084TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4085 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004086 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004087}
4088
chaviwfd6d3512019-03-25 13:23:49 -07004089class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004090 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004091 InputDispatcherTest::SetUp();
4092
Chris Yea209fde2020-07-22 13:54:51 -07004093 std::shared_ptr<FakeApplicationHandle> application =
4094 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004095 mUnfocusedWindow =
4096 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004097 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4098 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4099 // window.
chaviw3277faf2021-05-19 16:45:23 -05004100 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07004101
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004102 mFocusedWindow =
4103 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4104 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004105 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07004106
4107 // Set focused application.
4108 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004109 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004110
4111 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004112 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004113 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004114 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004115 }
4116
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004117 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004118 InputDispatcherTest::TearDown();
4119
4120 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004121 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004122 }
4123
4124protected:
4125 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004126 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004127 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004128};
4129
4130// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4131// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4132// the onPointerDownOutsideFocus callback.
4133TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004134 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004135 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4136 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004137 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004138 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004139
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004140 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004141 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4142}
4143
4144// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4145// DOWN on the window that doesn't have focus. Ensure no window received the
4146// onPointerDownOutsideFocus callback.
4147TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004148 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004149 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004150 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004151 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004152
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004153 ASSERT_TRUE(mDispatcher->waitForIdle());
4154 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004155}
4156
4157// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4158// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4159TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004160 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4161 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004162 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004163 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004164
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004165 ASSERT_TRUE(mDispatcher->waitForIdle());
4166 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004167}
4168
4169// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4170// DOWN on the window that already has focus. Ensure no window received the
4171// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004172TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004173 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004174 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004175 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004176 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004177 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004178
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004179 ASSERT_TRUE(mDispatcher->waitForIdle());
4180 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004181}
4182
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004183// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4184// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4185TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4186 const MotionEvent event =
4187 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4188 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4189 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4190 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4191 .build();
4192 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4193 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4194 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4195
4196 ASSERT_TRUE(mDispatcher->waitForIdle());
4197 mFakePolicy->assertOnPointerDownWasNotCalled();
4198 // Ensure that the unfocused window did not receive any FOCUS events.
4199 mUnfocusedWindow->assertNoEvents();
4200}
4201
chaviwaf87b3e2019-10-01 16:59:28 -07004202// These tests ensures we can send touch events to a single client when there are multiple input
4203// windows that point to the same client token.
4204class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4205 virtual void SetUp() override {
4206 InputDispatcherTest::SetUp();
4207
Chris Yea209fde2020-07-22 13:54:51 -07004208 std::shared_ptr<FakeApplicationHandle> application =
4209 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004210 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4211 ADISPLAY_ID_DEFAULT);
4212 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
4213 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05004214 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004215 mWindow1->setFrame(Rect(0, 0, 100, 100));
4216
4217 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4218 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05004219 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004220 mWindow2->setFrame(Rect(100, 100, 200, 200));
4221
Arthur Hung72d8dc32020-03-28 00:48:39 +00004222 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004223 }
4224
4225protected:
4226 sp<FakeWindowHandle> mWindow1;
4227 sp<FakeWindowHandle> mWindow2;
4228
4229 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004230 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004231 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4232 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004233 }
4234
4235 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4236 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004237 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004238 InputEvent* event = window->consume();
4239
4240 ASSERT_NE(nullptr, event) << name.c_str()
4241 << ": consumer should have returned non-NULL event.";
4242
4243 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4244 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4245 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4246
4247 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004248 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004249
4250 for (size_t i = 0; i < points.size(); i++) {
4251 float expectedX = points[i].x;
4252 float expectedY = points[i].y;
4253
4254 EXPECT_EQ(expectedX, motionEvent.getX(i))
4255 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4256 << ", got " << motionEvent.getX(i);
4257 EXPECT_EQ(expectedY, motionEvent.getY(i))
4258 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4259 << ", got " << motionEvent.getY(i);
4260 }
4261 }
chaviw9eaa22c2020-07-01 16:21:27 -07004262
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004263 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004264 std::vector<PointF> expectedPoints) {
4265 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4266 ADISPLAY_ID_DEFAULT, touchedPoints);
4267 mDispatcher->notifyMotion(&motionArgs);
4268
4269 // Always consume from window1 since it's the window that has the InputReceiver
4270 consumeMotionEvent(mWindow1, action, expectedPoints);
4271 }
chaviwaf87b3e2019-10-01 16:59:28 -07004272};
4273
4274TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4275 // Touch Window 1
4276 PointF touchedPoint = {10, 10};
4277 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004278 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004279
4280 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004281 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004282
4283 // Touch Window 2
4284 touchedPoint = {150, 150};
4285 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004286 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004287}
4288
chaviw9eaa22c2020-07-01 16:21:27 -07004289TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4290 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004291 mWindow2->setWindowScale(0.5f, 0.5f);
4292
4293 // Touch Window 1
4294 PointF touchedPoint = {10, 10};
4295 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004296 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004297 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004298 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004299
4300 // Touch Window 2
4301 touchedPoint = {150, 150};
4302 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004303 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4304 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004305
chaviw9eaa22c2020-07-01 16:21:27 -07004306 // Update the transform so rotation is set
4307 mWindow2->setWindowTransform(0, -1, 1, 0);
4308 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4309 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004310}
4311
chaviw9eaa22c2020-07-01 16:21:27 -07004312TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004313 mWindow2->setWindowScale(0.5f, 0.5f);
4314
4315 // Touch Window 1
4316 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4317 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004318 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004319
4320 // Touch Window 2
4321 int32_t actionPointerDown =
4322 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004323 touchedPoints.push_back(PointF{150, 150});
4324 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4325 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004326
chaviw9eaa22c2020-07-01 16:21:27 -07004327 // Release Window 2
4328 int32_t actionPointerUp =
4329 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4330 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4331 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004332
chaviw9eaa22c2020-07-01 16:21:27 -07004333 // Update the transform so rotation is set for Window 2
4334 mWindow2->setWindowTransform(0, -1, 1, 0);
4335 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4336 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004337}
4338
chaviw9eaa22c2020-07-01 16:21:27 -07004339TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004340 mWindow2->setWindowScale(0.5f, 0.5f);
4341
4342 // Touch Window 1
4343 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4344 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004345 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004346
4347 // Touch Window 2
4348 int32_t actionPointerDown =
4349 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004350 touchedPoints.push_back(PointF{150, 150});
4351 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004352
chaviw9eaa22c2020-07-01 16:21:27 -07004353 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004354
4355 // Move both windows
4356 touchedPoints = {{20, 20}, {175, 175}};
4357 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4358 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4359
chaviw9eaa22c2020-07-01 16:21:27 -07004360 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004361
chaviw9eaa22c2020-07-01 16:21:27 -07004362 // Release Window 2
4363 int32_t actionPointerUp =
4364 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4365 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4366 expectedPoints.pop_back();
4367
4368 // Touch Window 2
4369 mWindow2->setWindowTransform(0, -1, 1, 0);
4370 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4371 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4372
4373 // Move both windows
4374 touchedPoints = {{20, 20}, {175, 175}};
4375 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4376 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4377
4378 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004379}
4380
4381TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4382 mWindow1->setWindowScale(0.5f, 0.5f);
4383
4384 // Touch Window 1
4385 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4386 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004387 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004388
4389 // Touch Window 2
4390 int32_t actionPointerDown =
4391 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004392 touchedPoints.push_back(PointF{150, 150});
4393 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004394
chaviw9eaa22c2020-07-01 16:21:27 -07004395 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004396
4397 // Move both windows
4398 touchedPoints = {{20, 20}, {175, 175}};
4399 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4400 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4401
chaviw9eaa22c2020-07-01 16:21:27 -07004402 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004403}
4404
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004405class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4406 virtual void SetUp() override {
4407 InputDispatcherTest::SetUp();
4408
Chris Yea209fde2020-07-22 13:54:51 -07004409 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004410 mApplication->setDispatchingTimeout(20ms);
4411 mWindow =
4412 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4413 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004414 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004415 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004416 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4417 // window.
chaviw3277faf2021-05-19 16:45:23 -05004418 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004419
4420 // Set focused application.
4421 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4422
4423 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004424 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004425 mWindow->consumeFocusEvent(true);
4426 }
4427
4428 virtual void TearDown() override {
4429 InputDispatcherTest::TearDown();
4430 mWindow.clear();
4431 }
4432
4433protected:
Chris Yea209fde2020-07-22 13:54:51 -07004434 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004435 sp<FakeWindowHandle> mWindow;
4436 static constexpr PointF WINDOW_LOCATION = {20, 20};
4437
4438 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004439 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004440 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4441 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004442 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004443 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4444 WINDOW_LOCATION));
4445 }
4446};
4447
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004448// Send a tap and respond, which should not cause an ANR.
4449TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4450 tapOnWindow();
4451 mWindow->consumeMotionDown();
4452 mWindow->consumeMotionUp();
4453 ASSERT_TRUE(mDispatcher->waitForIdle());
4454 mFakePolicy->assertNotifyAnrWasNotCalled();
4455}
4456
4457// Send a regular key and respond, which should not cause an ANR.
4458TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004459 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004460 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4461 ASSERT_TRUE(mDispatcher->waitForIdle());
4462 mFakePolicy->assertNotifyAnrWasNotCalled();
4463}
4464
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004465TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4466 mWindow->setFocusable(false);
4467 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4468 mWindow->consumeFocusEvent(false);
4469
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004470 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004471 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004472 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4473 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004474 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004475 // Key will not go to window because we have no focused window.
4476 // The 'no focused window' ANR timer should start instead.
4477
4478 // Now, the focused application goes away.
4479 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4480 // The key should get dropped and there should be no ANR.
4481
4482 ASSERT_TRUE(mDispatcher->waitForIdle());
4483 mFakePolicy->assertNotifyAnrWasNotCalled();
4484}
4485
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004486// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004487// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4488// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004489TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004490 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004491 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4492 WINDOW_LOCATION));
4493
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004494 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4495 ASSERT_TRUE(sequenceNum);
4496 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004497 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004498
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004499 mWindow->finishEvent(*sequenceNum);
4500 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4501 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004502 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004503 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004504}
4505
4506// Send a key to the app and have the app not respond right away.
4507TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4508 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004509 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004510 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4511 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004512 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004513 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004514 ASSERT_TRUE(mDispatcher->waitForIdle());
4515}
4516
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004517// We have a focused application, but no focused window
4518TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004519 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004520 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4521 mWindow->consumeFocusEvent(false);
4522
4523 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004524 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004525 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4526 WINDOW_LOCATION));
4527 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4528 mDispatcher->waitForIdle();
4529 mFakePolicy->assertNotifyAnrWasNotCalled();
4530
4531 // Once a focused event arrives, we get an ANR for this application
4532 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4533 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004534 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004535 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004536 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004537 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004538 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004539 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004540 ASSERT_TRUE(mDispatcher->waitForIdle());
4541}
4542
4543// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004544// Make sure that we don't notify policy twice about the same ANR.
4545TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004546 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004547 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4548 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004549
4550 // Once a focused event arrives, we get an ANR for this application
4551 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4552 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004553 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004554 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004555 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004556 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004557 const std::chrono::duration appTimeout =
4558 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004559 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004560
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004561 std::this_thread::sleep_for(appTimeout);
4562 // ANR should not be raised again. It is up to policy to do that if it desires.
4563 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004564
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004565 // If we now get a focused window, the ANR should stop, but the policy handles that via
4566 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004567 ASSERT_TRUE(mDispatcher->waitForIdle());
4568}
4569
4570// We have a focused application, but no focused window
4571TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004572 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004573 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4574 mWindow->consumeFocusEvent(false);
4575
4576 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004577 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004578 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004579 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4580 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004581
4582 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004583 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004584
4585 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004586 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004587 ASSERT_TRUE(mDispatcher->waitForIdle());
4588 mWindow->assertNoEvents();
4589}
4590
4591/**
4592 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4593 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4594 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4595 * the ANR mechanism should still work.
4596 *
4597 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4598 * DOWN event, while not responding on the second one.
4599 */
4600TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4601 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4602 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4603 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4604 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4605 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004606 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004607
4608 // Now send ACTION_UP, with identical timestamp
4609 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4610 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4611 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4612 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004613 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004614
4615 // We have now sent down and up. Let's consume first event and then ANR on the second.
4616 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4617 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004618 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004619}
4620
4621// If an app is not responding to a key event, gesture monitors should continue to receive
4622// new motion events
4623TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnKey) {
4624 FakeMonitorReceiver monitor =
4625 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4626 true /*isGestureMonitor*/);
4627
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004628 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4629 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004630 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004631 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004632
4633 // Stuck on the ACTION_UP
4634 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004635 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004636
4637 // New tap will go to the gesture monitor, but not to the window
4638 tapOnWindow();
4639 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4640 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4641
4642 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4643 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004644 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004645 mWindow->assertNoEvents();
4646 monitor.assertNoEvents();
4647}
4648
4649// If an app is not responding to a motion event, gesture monitors should continue to receive
4650// new motion events
4651TEST_F(InputDispatcherSingleWindowAnr, GestureMonitors_ReceiveEventsDuringAppAnrOnMotion) {
4652 FakeMonitorReceiver monitor =
4653 FakeMonitorReceiver(mDispatcher, "Gesture monitor", ADISPLAY_ID_DEFAULT,
4654 true /*isGestureMonitor*/);
4655
4656 tapOnWindow();
4657 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4658 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4659
4660 mWindow->consumeMotionDown();
4661 // Stuck on the ACTION_UP
4662 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004663 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004664
4665 // New tap will go to the gesture monitor, but not to the window
4666 tapOnWindow();
4667 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
4668 monitor.consumeMotionUp(ADISPLAY_ID_DEFAULT);
4669
4670 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4671 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004672 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004673 mWindow->assertNoEvents();
4674 monitor.assertNoEvents();
4675}
4676
4677// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4678// process events, you don't get an anr. When the window later becomes unresponsive again, you
4679// get an ANR again.
4680// 1. tap -> block on ACTION_UP -> receive ANR
4681// 2. consume all pending events (= queue becomes healthy again)
4682// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4683TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4684 tapOnWindow();
4685
4686 mWindow->consumeMotionDown();
4687 // Block on ACTION_UP
4688 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004689 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004690 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4691 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004692 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004693 mWindow->assertNoEvents();
4694
4695 tapOnWindow();
4696 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004697 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004698 mWindow->consumeMotionUp();
4699
4700 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004701 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004702 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004703 mWindow->assertNoEvents();
4704}
4705
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004706// If a connection remains unresponsive for a while, make sure policy is only notified once about
4707// it.
4708TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004709 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004710 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4711 WINDOW_LOCATION));
4712
4713 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004714 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004715 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004716 // 'notifyConnectionUnresponsive' should only be called once per connection
4717 mFakePolicy->assertNotifyAnrWasNotCalled();
4718 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004719 mWindow->consumeMotionDown();
4720 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4721 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4722 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004723 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004724 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004725 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004726}
4727
4728/**
4729 * If a window is processing a motion event, and then a key event comes in, the key event should
4730 * not to to the focused window until the motion is processed.
4731 *
4732 * Warning!!!
4733 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4734 * and the injection timeout that we specify when injecting the key.
4735 * We must have the injection timeout (10ms) be smaller than
4736 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4737 *
4738 * If that value changes, this test should also change.
4739 */
4740TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4741 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4742 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4743
4744 tapOnWindow();
4745 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4746 ASSERT_TRUE(downSequenceNum);
4747 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4748 ASSERT_TRUE(upSequenceNum);
4749 // Don't finish the events yet, and send a key
4750 // Injection will "succeed" because we will eventually give up and send the key to the focused
4751 // window even if motions are still being processed. But because the injection timeout is short,
4752 // we will receive INJECTION_TIMED_OUT as the result.
4753
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004754 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004755 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004756 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4757 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004758 // Key will not be sent to the window, yet, because the window is still processing events
4759 // and the key remains pending, waiting for the touch events to be processed
4760 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4761 ASSERT_FALSE(keySequenceNum);
4762
4763 std::this_thread::sleep_for(500ms);
4764 // if we wait long enough though, dispatcher will give up, and still send the key
4765 // to the focused window, even though we have not yet finished the motion event
4766 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4767 mWindow->finishEvent(*downSequenceNum);
4768 mWindow->finishEvent(*upSequenceNum);
4769}
4770
4771/**
4772 * If a window is processing a motion event, and then a key event comes in, the key event should
4773 * not go to the focused window until the motion is processed.
4774 * If then a new motion comes in, then the pending key event should be going to the currently
4775 * focused window right away.
4776 */
4777TEST_F(InputDispatcherSingleWindowAnr,
4778 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4779 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4780 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4781
4782 tapOnWindow();
4783 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4784 ASSERT_TRUE(downSequenceNum);
4785 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4786 ASSERT_TRUE(upSequenceNum);
4787 // Don't finish the events yet, and send a key
4788 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004789 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004790 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004791 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004792 // At this point, key is still pending, and should not be sent to the application yet.
4793 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4794 ASSERT_FALSE(keySequenceNum);
4795
4796 // Now tap down again. It should cause the pending key to go to the focused window right away.
4797 tapOnWindow();
4798 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4799 // the other events yet. We can finish events in any order.
4800 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4801 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4802 mWindow->consumeMotionDown();
4803 mWindow->consumeMotionUp();
4804 mWindow->assertNoEvents();
4805}
4806
4807class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4808 virtual void SetUp() override {
4809 InputDispatcherTest::SetUp();
4810
Chris Yea209fde2020-07-22 13:54:51 -07004811 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004812 mApplication->setDispatchingTimeout(10ms);
4813 mUnfocusedWindow =
4814 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4815 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4816 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4817 // window.
4818 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004819 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4820 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4821 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004822
4823 mFocusedWindow =
4824 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004825 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004826 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004827 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004828
4829 // Set focused application.
4830 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004831 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004832
4833 // Expect one focus window exist in display.
4834 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004835 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004836 mFocusedWindow->consumeFocusEvent(true);
4837 }
4838
4839 virtual void TearDown() override {
4840 InputDispatcherTest::TearDown();
4841
4842 mUnfocusedWindow.clear();
4843 mFocusedWindow.clear();
4844 }
4845
4846protected:
Chris Yea209fde2020-07-22 13:54:51 -07004847 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004848 sp<FakeWindowHandle> mUnfocusedWindow;
4849 sp<FakeWindowHandle> mFocusedWindow;
4850 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4851 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4852 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4853
4854 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4855
4856 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4857
4858private:
4859 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004860 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004861 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4862 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004863 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004864 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4865 location));
4866 }
4867};
4868
4869// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4870// should be ANR'd first.
4871TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004872 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004873 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4874 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004875 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004876 mFocusedWindow->consumeMotionDown();
4877 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4878 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4879 // We consumed all events, so no ANR
4880 ASSERT_TRUE(mDispatcher->waitForIdle());
4881 mFakePolicy->assertNotifyAnrWasNotCalled();
4882
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004883 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004884 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4885 FOCUSED_WINDOW_LOCATION));
4886 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4887 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004888
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 Vishniakou234129c2020-10-22 22:28:12 -05004892 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4893 // sequence to make it consistent
4894 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004895 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004896 mFocusedWindow->consumeMotionDown();
4897 // This cancel is generated because the connection was unresponsive
4898 mFocusedWindow->consumeMotionCancel();
4899 mFocusedWindow->assertNoEvents();
4900 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004901 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004902 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004903 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004904}
4905
4906// If we have 2 windows with identical timeouts that are both unresponsive,
4907// it doesn't matter which order they should have ANR.
4908// But we should receive ANR for both.
4909TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4910 // Set the timeout for unfocused window to match the focused window
4911 mUnfocusedWindow->setDispatchingTimeout(10ms);
4912 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4913
4914 tapOnFocusedWindow();
4915 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004916 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4917 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004918
4919 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004920 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4921 mFocusedWindow->getToken() == anrConnectionToken2);
4922 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4923 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004924
4925 ASSERT_TRUE(mDispatcher->waitForIdle());
4926 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004927
4928 mFocusedWindow->consumeMotionDown();
4929 mFocusedWindow->consumeMotionUp();
4930 mUnfocusedWindow->consumeMotionOutside();
4931
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004932 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4933 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004934
4935 // Both applications should be marked as responsive, in any order
4936 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4937 mFocusedWindow->getToken() == responsiveToken2);
4938 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4939 mUnfocusedWindow->getToken() == responsiveToken2);
4940 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004941}
4942
4943// If a window is already not responding, the second tap on the same window should be ignored.
4944// We should also log an error to account for the dropped event (not tested here).
4945// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4946TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4947 tapOnFocusedWindow();
4948 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4949 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4950 // Receive the events, but don't respond
4951 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4952 ASSERT_TRUE(downEventSequenceNum);
4953 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4954 ASSERT_TRUE(upEventSequenceNum);
4955 const std::chrono::duration timeout =
4956 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004957 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004958
4959 // Tap once again
4960 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004961 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004962 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4963 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004964 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004965 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4966 FOCUSED_WINDOW_LOCATION));
4967 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4968 // valid touch target
4969 mUnfocusedWindow->assertNoEvents();
4970
4971 // Consume the first tap
4972 mFocusedWindow->finishEvent(*downEventSequenceNum);
4973 mFocusedWindow->finishEvent(*upEventSequenceNum);
4974 ASSERT_TRUE(mDispatcher->waitForIdle());
4975 // The second tap did not go to the focused window
4976 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004977 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004978 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004979 mFakePolicy->assertNotifyAnrWasNotCalled();
4980}
4981
4982// If you tap outside of all windows, there will not be ANR
4983TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004984 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004985 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4986 LOCATION_OUTSIDE_ALL_WINDOWS));
4987 ASSERT_TRUE(mDispatcher->waitForIdle());
4988 mFakePolicy->assertNotifyAnrWasNotCalled();
4989}
4990
4991// Since the focused window is paused, tapping on it should not produce any events
4992TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4993 mFocusedWindow->setPaused(true);
4994 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4995
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004996 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004997 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4998 FOCUSED_WINDOW_LOCATION));
4999
5000 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5001 ASSERT_TRUE(mDispatcher->waitForIdle());
5002 // Should not ANR because the window is paused, and touches shouldn't go to it
5003 mFakePolicy->assertNotifyAnrWasNotCalled();
5004
5005 mFocusedWindow->assertNoEvents();
5006 mUnfocusedWindow->assertNoEvents();
5007}
5008
5009/**
5010 * If a window is processing a motion event, and then a key event comes in, the key event should
5011 * not to to the focused window until the motion is processed.
5012 * If a different window becomes focused at this time, the key should go to that window instead.
5013 *
5014 * Warning!!!
5015 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5016 * and the injection timeout that we specify when injecting the key.
5017 * We must have the injection timeout (10ms) be smaller than
5018 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5019 *
5020 * If that value changes, this test should also change.
5021 */
5022TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5023 // Set a long ANR timeout to prevent it from triggering
5024 mFocusedWindow->setDispatchingTimeout(2s);
5025 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5026
5027 tapOnUnfocusedWindow();
5028 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5029 ASSERT_TRUE(downSequenceNum);
5030 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5031 ASSERT_TRUE(upSequenceNum);
5032 // Don't finish the events yet, and send a key
5033 // Injection will succeed because we will eventually give up and send the key to the focused
5034 // window even if motions are still being processed.
5035
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005036 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005037 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005038 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5039 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005040 // Key will not be sent to the window, yet, because the window is still processing events
5041 // and the key remains pending, waiting for the touch events to be processed
5042 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5043 ASSERT_FALSE(keySequenceNum);
5044
5045 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005046 mFocusedWindow->setFocusable(false);
5047 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005048 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005049 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005050
5051 // Focus events should precede the key events
5052 mUnfocusedWindow->consumeFocusEvent(true);
5053 mFocusedWindow->consumeFocusEvent(false);
5054
5055 // Finish the tap events, which should unblock dispatcher
5056 mUnfocusedWindow->finishEvent(*downSequenceNum);
5057 mUnfocusedWindow->finishEvent(*upSequenceNum);
5058
5059 // Now that all queues are cleared and no backlog in the connections, the key event
5060 // can finally go to the newly focused "mUnfocusedWindow".
5061 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5062 mFocusedWindow->assertNoEvents();
5063 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005064 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005065}
5066
5067// When the touch stream is split across 2 windows, and one of them does not respond,
5068// then ANR should be raised and the touch should be canceled for the unresponsive window.
5069// The other window should not be affected by that.
5070TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5071 // Touch Window 1
5072 NotifyMotionArgs motionArgs =
5073 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5074 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5075 mDispatcher->notifyMotion(&motionArgs);
5076 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5077 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5078
5079 // Touch Window 2
5080 int32_t actionPointerDown =
5081 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
5082
5083 motionArgs =
5084 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5085 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
5086 mDispatcher->notifyMotion(&motionArgs);
5087
5088 const std::chrono::duration timeout =
5089 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005090 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005091
5092 mUnfocusedWindow->consumeMotionDown();
5093 mFocusedWindow->consumeMotionDown();
5094 // Focused window may or may not receive ACTION_MOVE
5095 // But it should definitely receive ACTION_CANCEL due to the ANR
5096 InputEvent* event;
5097 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5098 ASSERT_TRUE(moveOrCancelSequenceNum);
5099 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5100 ASSERT_NE(nullptr, event);
5101 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5102 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5103 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5104 mFocusedWindow->consumeMotionCancel();
5105 } else {
5106 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5107 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005108 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005109 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005110
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005111 mUnfocusedWindow->assertNoEvents();
5112 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005113 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005114}
5115
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005116/**
5117 * If we have no focused window, and a key comes in, we start the ANR timer.
5118 * The focused application should add a focused window before the timer runs out to prevent ANR.
5119 *
5120 * If the user touches another application during this time, the key should be dropped.
5121 * Next, if a new focused window comes in, without toggling the focused application,
5122 * then no ANR should occur.
5123 *
5124 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5125 * but in some cases the policy may not update the focused application.
5126 */
5127TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5128 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5129 std::make_shared<FakeApplicationHandle>();
5130 focusedApplication->setDispatchingTimeout(60ms);
5131 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5132 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5133 mFocusedWindow->setFocusable(false);
5134
5135 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5136 mFocusedWindow->consumeFocusEvent(false);
5137
5138 // Send a key. The ANR timer should start because there is no focused window.
5139 // 'focusedApplication' will get blamed if this timer completes.
5140 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005141 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005142 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005143 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5144 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005145 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005146
5147 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5148 // then the injected touches won't cause the focused event to get dropped.
5149 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5150 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5151 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5152 // For this test, it means that the key would get delivered to the window once it becomes
5153 // focused.
5154 std::this_thread::sleep_for(10ms);
5155
5156 // Touch unfocused window. This should force the pending key to get dropped.
5157 NotifyMotionArgs motionArgs =
5158 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5159 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5160 mDispatcher->notifyMotion(&motionArgs);
5161
5162 // We do not consume the motion right away, because that would require dispatcher to first
5163 // process (== drop) the key event, and by that time, ANR will be raised.
5164 // Set the focused window first.
5165 mFocusedWindow->setFocusable(true);
5166 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5167 setFocusedWindow(mFocusedWindow);
5168 mFocusedWindow->consumeFocusEvent(true);
5169 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5170 // to another application. This could be a bug / behaviour in the policy.
5171
5172 mUnfocusedWindow->consumeMotionDown();
5173
5174 ASSERT_TRUE(mDispatcher->waitForIdle());
5175 // Should not ANR because we actually have a focused window. It was just added too slowly.
5176 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5177}
5178
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005179// These tests ensure we cannot send touch events to a window that's positioned behind a window
5180// that has feature NO_INPUT_CHANNEL.
5181// Layout:
5182// Top (closest to user)
5183// mNoInputWindow (above all windows)
5184// mBottomWindow
5185// Bottom (furthest from user)
5186class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5187 virtual void SetUp() override {
5188 InputDispatcherTest::SetUp();
5189
5190 mApplication = std::make_shared<FakeApplicationHandle>();
5191 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5192 "Window without input channel", ADISPLAY_ID_DEFAULT,
5193 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5194
chaviw3277faf2021-05-19 16:45:23 -05005195 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005196 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5197 // It's perfectly valid for this window to not have an associated input channel
5198
5199 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5200 ADISPLAY_ID_DEFAULT);
5201 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5202
5203 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5204 }
5205
5206protected:
5207 std::shared_ptr<FakeApplicationHandle> mApplication;
5208 sp<FakeWindowHandle> mNoInputWindow;
5209 sp<FakeWindowHandle> mBottomWindow;
5210};
5211
5212TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5213 PointF touchedPoint = {10, 10};
5214
5215 NotifyMotionArgs motionArgs =
5216 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5217 ADISPLAY_ID_DEFAULT, {touchedPoint});
5218 mDispatcher->notifyMotion(&motionArgs);
5219
5220 mNoInputWindow->assertNoEvents();
5221 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5222 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5223 // and therefore should prevent mBottomWindow from receiving touches
5224 mBottomWindow->assertNoEvents();
5225}
5226
5227/**
5228 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5229 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5230 */
5231TEST_F(InputDispatcherMultiWindowOcclusionTests,
5232 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5233 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5234 "Window with input channel and NO_INPUT_CHANNEL",
5235 ADISPLAY_ID_DEFAULT);
5236
chaviw3277faf2021-05-19 16:45:23 -05005237 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005238 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5239 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5240
5241 PointF touchedPoint = {10, 10};
5242
5243 NotifyMotionArgs motionArgs =
5244 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5245 ADISPLAY_ID_DEFAULT, {touchedPoint});
5246 mDispatcher->notifyMotion(&motionArgs);
5247
5248 mNoInputWindow->assertNoEvents();
5249 mBottomWindow->assertNoEvents();
5250}
5251
Vishnu Nair958da932020-08-21 17:12:37 -07005252class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5253protected:
5254 std::shared_ptr<FakeApplicationHandle> mApp;
5255 sp<FakeWindowHandle> mWindow;
5256 sp<FakeWindowHandle> mMirror;
5257
5258 virtual void SetUp() override {
5259 InputDispatcherTest::SetUp();
5260 mApp = std::make_shared<FakeApplicationHandle>();
5261 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5262 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5263 mWindow->getToken());
5264 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5265 mWindow->setFocusable(true);
5266 mMirror->setFocusable(true);
5267 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5268 }
5269};
5270
5271TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5272 // Request focus on a mirrored window
5273 setFocusedWindow(mMirror);
5274
5275 // window gets focused
5276 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005277 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5278 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005279 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5280}
5281
5282// A focused & mirrored window remains focused only if the window and its mirror are both
5283// focusable.
5284TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5285 setFocusedWindow(mMirror);
5286
5287 // window gets focused
5288 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005289 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5290 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005291 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005292 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5293 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005294 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5295
5296 mMirror->setFocusable(false);
5297 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5298
5299 // window loses focus since one of the windows associated with the token in not focusable
5300 mWindow->consumeFocusEvent(false);
5301
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005302 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5303 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005304 mWindow->assertNoEvents();
5305}
5306
5307// A focused & mirrored window remains focused until the window and its mirror both become
5308// invisible.
5309TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5310 setFocusedWindow(mMirror);
5311
5312 // window gets focused
5313 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005314 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5315 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005316 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005317 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5318 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005319 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5320
5321 mMirror->setVisible(false);
5322 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5323
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005324 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5325 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005326 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005327 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5328 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005329 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5330
5331 mWindow->setVisible(false);
5332 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5333
5334 // window loses focus only after all windows associated with the token become invisible.
5335 mWindow->consumeFocusEvent(false);
5336
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005337 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5338 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005339 mWindow->assertNoEvents();
5340}
5341
5342// A focused & mirrored window remains focused until both windows are removed.
5343TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5344 setFocusedWindow(mMirror);
5345
5346 // window gets focused
5347 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005348 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5349 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005350 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005351 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5352 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005353 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5354
5355 // single window is removed but the window token remains focused
5356 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5357
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005358 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5359 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005360 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005361 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5362 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005363 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5364
5365 // Both windows are removed
5366 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5367 mWindow->consumeFocusEvent(false);
5368
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005369 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5370 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005371 mWindow->assertNoEvents();
5372}
5373
5374// Focus request can be pending until one window becomes visible.
5375TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5376 // Request focus on an invisible mirror.
5377 mWindow->setVisible(false);
5378 mMirror->setVisible(false);
5379 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5380 setFocusedWindow(mMirror);
5381
5382 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005383 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005384 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005385 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005386
5387 mMirror->setVisible(true);
5388 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5389
5390 // window gets focused
5391 mWindow->consumeFocusEvent(true);
5392 // window gets the pending key event
5393 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5394}
Prabir Pradhan99987712020-11-10 18:43:05 -08005395
5396class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5397protected:
5398 std::shared_ptr<FakeApplicationHandle> mApp;
5399 sp<FakeWindowHandle> mWindow;
5400 sp<FakeWindowHandle> mSecondWindow;
5401
5402 void SetUp() override {
5403 InputDispatcherTest::SetUp();
5404 mApp = std::make_shared<FakeApplicationHandle>();
5405 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5406 mWindow->setFocusable(true);
5407 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5408 mSecondWindow->setFocusable(true);
5409
5410 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5411 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5412
5413 setFocusedWindow(mWindow);
5414 mWindow->consumeFocusEvent(true);
5415 }
5416
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005417 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5418 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005419 mDispatcher->notifyPointerCaptureChanged(&args);
5420 }
5421
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005422 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5423 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005424 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005425 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5426 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005427 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005428 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005429 }
5430};
5431
5432TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5433 // Ensure that capture cannot be obtained for unfocused windows.
5434 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5435 mFakePolicy->assertSetPointerCaptureNotCalled();
5436 mSecondWindow->assertNoEvents();
5437
5438 // Ensure that capture can be enabled from the focus window.
5439 requestAndVerifyPointerCapture(mWindow, true);
5440
5441 // Ensure that capture cannot be disabled from a window that does not have capture.
5442 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5443 mFakePolicy->assertSetPointerCaptureNotCalled();
5444
5445 // Ensure that capture can be disabled from the window with capture.
5446 requestAndVerifyPointerCapture(mWindow, false);
5447}
5448
5449TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005450 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005451
5452 setFocusedWindow(mSecondWindow);
5453
5454 // Ensure that the capture disabled event was sent first.
5455 mWindow->consumeCaptureEvent(false);
5456 mWindow->consumeFocusEvent(false);
5457 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005458 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005459
5460 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005461 notifyPointerCaptureChanged({});
5462 notifyPointerCaptureChanged(request);
5463 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005464 mWindow->assertNoEvents();
5465 mSecondWindow->assertNoEvents();
5466 mFakePolicy->assertSetPointerCaptureNotCalled();
5467}
5468
5469TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005470 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005471
5472 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005473 notifyPointerCaptureChanged({});
5474 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005475
5476 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005477 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005478 mWindow->consumeCaptureEvent(false);
5479 mWindow->assertNoEvents();
5480}
5481
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005482TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5483 requestAndVerifyPointerCapture(mWindow, true);
5484
5485 // The first window loses focus.
5486 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005487 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005488 mWindow->consumeCaptureEvent(false);
5489
5490 // Request Pointer Capture from the second window before the notification from InputReader
5491 // arrives.
5492 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005493 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005494
5495 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005496 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005497
5498 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005499 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005500
5501 mSecondWindow->consumeFocusEvent(true);
5502 mSecondWindow->consumeCaptureEvent(true);
5503}
5504
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005505TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5506 // App repeatedly enables and disables capture.
5507 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5508 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5509 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5510 mFakePolicy->assertSetPointerCaptureCalled(false);
5511 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5512 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5513
5514 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5515 // first request is now stale, this should do nothing.
5516 notifyPointerCaptureChanged(firstRequest);
5517 mWindow->assertNoEvents();
5518
5519 // InputReader notifies that the second request was enabled.
5520 notifyPointerCaptureChanged(secondRequest);
5521 mWindow->consumeCaptureEvent(true);
5522}
5523
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005524class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5525protected:
5526 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005527
5528 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5529 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5530
5531 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5532 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5533
5534 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5535 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5536 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5537 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5538 MAXIMUM_OBSCURING_OPACITY);
5539
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005540 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005541 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005542 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005543
5544 sp<FakeWindowHandle> mTouchWindow;
5545
5546 virtual void SetUp() override {
5547 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005548 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005549 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5550 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5551 }
5552
5553 virtual void TearDown() override {
5554 InputDispatcherTest::TearDown();
5555 mTouchWindow.clear();
5556 }
5557
chaviw3277faf2021-05-19 16:45:23 -05005558 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5559 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005560 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005561 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005562 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005563 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005564 return window;
5565 }
5566
5567 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5568 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5569 sp<FakeWindowHandle> window =
5570 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5571 // Generate an arbitrary PID based on the UID
5572 window->setOwnerInfo(1777 + (uid % 10000), uid);
5573 return window;
5574 }
5575
5576 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5577 NotifyMotionArgs args =
5578 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5579 ADISPLAY_ID_DEFAULT, points);
5580 mDispatcher->notifyMotion(&args);
5581 }
5582};
5583
5584TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005585 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005586 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005587 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005588
5589 touch();
5590
5591 mTouchWindow->assertNoEvents();
5592}
5593
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005594TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005595 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5596 const sp<FakeWindowHandle>& w =
5597 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5598 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5599
5600 touch();
5601
5602 mTouchWindow->assertNoEvents();
5603}
5604
5605TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005606 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5607 const sp<FakeWindowHandle>& w =
5608 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5609 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5610
5611 touch();
5612
5613 w->assertNoEvents();
5614}
5615
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005616TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005617 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5618 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005619
5620 touch();
5621
5622 mTouchWindow->consumeAnyMotionDown();
5623}
5624
5625TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005626 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005627 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005628 w->setFrame(Rect(0, 0, 50, 50));
5629 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005630
5631 touch({PointF{100, 100}});
5632
5633 mTouchWindow->consumeAnyMotionDown();
5634}
5635
5636TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005637 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005638 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005639 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5640
5641 touch();
5642
5643 mTouchWindow->consumeAnyMotionDown();
5644}
5645
5646TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5647 const sp<FakeWindowHandle>& w =
5648 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5649 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005650
5651 touch();
5652
5653 mTouchWindow->consumeAnyMotionDown();
5654}
5655
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005656TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5657 const sp<FakeWindowHandle>& w =
5658 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5659 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5660
5661 touch();
5662
5663 w->assertNoEvents();
5664}
5665
5666/**
5667 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5668 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5669 * window, the occluding window will still receive ACTION_OUTSIDE event.
5670 */
5671TEST_F(InputDispatcherUntrustedTouchesTest,
5672 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5673 const sp<FakeWindowHandle>& w =
5674 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005675 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005676 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5677
5678 touch();
5679
5680 w->consumeMotionOutside();
5681}
5682
5683TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5684 const sp<FakeWindowHandle>& w =
5685 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005686 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005687 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5688
5689 touch();
5690
5691 InputEvent* event = w->consume();
5692 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
5693 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5694 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getX());
5695 EXPECT_EQ(0.0f, motionEvent.getRawPointerCoords(0)->getY());
5696}
5697
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005698TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005699 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005700 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5701 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005702 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5703
5704 touch();
5705
5706 mTouchWindow->consumeAnyMotionDown();
5707}
5708
5709TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5710 const sp<FakeWindowHandle>& w =
5711 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5712 MAXIMUM_OBSCURING_OPACITY);
5713 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005714
5715 touch();
5716
5717 mTouchWindow->consumeAnyMotionDown();
5718}
5719
5720TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005721 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005722 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5723 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005724 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5725
5726 touch();
5727
5728 mTouchWindow->assertNoEvents();
5729}
5730
5731TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5732 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5733 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005734 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5735 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005736 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005737 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5738 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005739 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5740
5741 touch();
5742
5743 mTouchWindow->assertNoEvents();
5744}
5745
5746TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5747 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5748 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005749 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5750 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005751 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005752 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5753 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005754 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5755
5756 touch();
5757
5758 mTouchWindow->consumeAnyMotionDown();
5759}
5760
5761TEST_F(InputDispatcherUntrustedTouchesTest,
5762 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5763 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005764 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5765 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005766 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005767 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5768 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005769 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5770
5771 touch();
5772
5773 mTouchWindow->consumeAnyMotionDown();
5774}
5775
5776TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5777 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005778 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5779 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005780 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005781 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5782 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005783 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005784
5785 touch();
5786
5787 mTouchWindow->assertNoEvents();
5788}
5789
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005790TEST_F(InputDispatcherUntrustedTouchesTest,
5791 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5792 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005793 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5794 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005795 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005796 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5797 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005798 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5799
5800 touch();
5801
5802 mTouchWindow->assertNoEvents();
5803}
5804
5805TEST_F(InputDispatcherUntrustedTouchesTest,
5806 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5807 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005808 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5809 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005810 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005811 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5812 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005813 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5814
5815 touch();
5816
5817 mTouchWindow->consumeAnyMotionDown();
5818}
5819
5820TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5821 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005822 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5823 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005824 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5825
5826 touch();
5827
5828 mTouchWindow->consumeAnyMotionDown();
5829}
5830
5831TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5832 const sp<FakeWindowHandle>& w =
5833 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5834 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5835
5836 touch();
5837
5838 mTouchWindow->consumeAnyMotionDown();
5839}
5840
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005841TEST_F(InputDispatcherUntrustedTouchesTest,
5842 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5843 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5844 const sp<FakeWindowHandle>& w =
5845 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5846 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5847
5848 touch();
5849
5850 mTouchWindow->assertNoEvents();
5851}
5852
5853TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5854 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5855 const sp<FakeWindowHandle>& w =
5856 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5857 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5858
5859 touch();
5860
5861 mTouchWindow->consumeAnyMotionDown();
5862}
5863
5864TEST_F(InputDispatcherUntrustedTouchesTest,
5865 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5866 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5867 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005868 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5869 OPACITY_ABOVE_THRESHOLD);
5870 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5871
5872 touch();
5873
5874 mTouchWindow->consumeAnyMotionDown();
5875}
5876
5877TEST_F(InputDispatcherUntrustedTouchesTest,
5878 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5879 const sp<FakeWindowHandle>& w1 =
5880 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5881 OPACITY_BELOW_THRESHOLD);
5882 const sp<FakeWindowHandle>& w2 =
5883 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5884 OPACITY_BELOW_THRESHOLD);
5885 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5886
5887 touch();
5888
5889 mTouchWindow->assertNoEvents();
5890}
5891
5892/**
5893 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5894 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5895 * (which alone would result in allowing touches) does not affect the blocking behavior.
5896 */
5897TEST_F(InputDispatcherUntrustedTouchesTest,
5898 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5899 const sp<FakeWindowHandle>& wB =
5900 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5901 OPACITY_BELOW_THRESHOLD);
5902 const sp<FakeWindowHandle>& wC =
5903 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5904 OPACITY_BELOW_THRESHOLD);
5905 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5906
5907 touch();
5908
5909 mTouchWindow->assertNoEvents();
5910}
5911
5912/**
5913 * This test is testing that a window from a different UID but with same application token doesn't
5914 * block the touch. Apps can share the application token for close UI collaboration for example.
5915 */
5916TEST_F(InputDispatcherUntrustedTouchesTest,
5917 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5918 const sp<FakeWindowHandle>& w =
5919 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5920 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005921 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5922
5923 touch();
5924
5925 mTouchWindow->consumeAnyMotionDown();
5926}
5927
arthurhungb89ccb02020-12-30 16:19:01 +08005928class InputDispatcherDragTests : public InputDispatcherTest {
5929protected:
5930 std::shared_ptr<FakeApplicationHandle> mApp;
5931 sp<FakeWindowHandle> mWindow;
5932 sp<FakeWindowHandle> mSecondWindow;
5933 sp<FakeWindowHandle> mDragWindow;
5934
5935 void SetUp() override {
5936 InputDispatcherTest::SetUp();
5937 mApp = std::make_shared<FakeApplicationHandle>();
5938 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5939 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005940 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005941
5942 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5943 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005944 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005945
5946 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5947 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5948 }
5949
5950 // Start performing drag, we will create a drag window and transfer touch to it.
5951 void performDrag() {
5952 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5953 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5954 {50, 50}))
5955 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5956
5957 // Window should receive motion event.
5958 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5959
5960 // The drag window covers the entire display
5961 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5962 mDispatcher->setInputWindows(
5963 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5964
5965 // Transfer touch focus to the drag window
5966 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5967 true /* isDragDrop */);
5968 mWindow->consumeMotionCancel();
5969 mDragWindow->consumeMotionDown();
5970 }
arthurhung6d4bed92021-03-17 11:59:33 +08005971
5972 // Start performing drag, we will create a drag window and transfer touch to it.
5973 void performStylusDrag() {
5974 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5975 injectMotionEvent(mDispatcher,
5976 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5977 AINPUT_SOURCE_STYLUS)
5978 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5979 .pointer(PointerBuilder(0,
5980 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5981 .x(50)
5982 .y(50))
5983 .build()));
5984 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5985
5986 // The drag window covers the entire display
5987 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5988 mDispatcher->setInputWindows(
5989 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5990
5991 // Transfer touch focus to the drag window
5992 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5993 true /* isDragDrop */);
5994 mWindow->consumeMotionCancel();
5995 mDragWindow->consumeMotionDown();
5996 }
arthurhungb89ccb02020-12-30 16:19:01 +08005997};
5998
5999TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
6000 performDrag();
6001
6002 // Move on window.
6003 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6004 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6005 ADISPLAY_ID_DEFAULT, {50, 50}))
6006 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6007 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6008 mWindow->consumeDragEvent(false, 50, 50);
6009 mSecondWindow->assertNoEvents();
6010
6011 // Move to another window.
6012 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6013 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6014 ADISPLAY_ID_DEFAULT, {150, 50}))
6015 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6016 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6017 mWindow->consumeDragEvent(true, 150, 50);
6018 mSecondWindow->consumeDragEvent(false, 50, 50);
6019
6020 // Move back to original window.
6021 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6022 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6023 ADISPLAY_ID_DEFAULT, {50, 50}))
6024 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6025 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6026 mWindow->consumeDragEvent(false, 50, 50);
6027 mSecondWindow->consumeDragEvent(true, -50, 50);
6028
6029 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6030 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6031 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6032 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6033 mWindow->assertNoEvents();
6034 mSecondWindow->assertNoEvents();
6035}
6036
arthurhungf452d0b2021-01-06 00:19:52 +08006037TEST_F(InputDispatcherDragTests, DragAndDrop) {
6038 performDrag();
6039
6040 // Move on window.
6041 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6042 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6043 ADISPLAY_ID_DEFAULT, {50, 50}))
6044 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6045 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6046 mWindow->consumeDragEvent(false, 50, 50);
6047 mSecondWindow->assertNoEvents();
6048
6049 // Move to another window.
6050 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6051 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6052 ADISPLAY_ID_DEFAULT, {150, 50}))
6053 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6054 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6055 mWindow->consumeDragEvent(true, 150, 50);
6056 mSecondWindow->consumeDragEvent(false, 50, 50);
6057
6058 // drop to another window.
6059 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6060 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6061 {150, 50}))
6062 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6063 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6064 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6065 mWindow->assertNoEvents();
6066 mSecondWindow->assertNoEvents();
6067}
6068
arthurhung6d4bed92021-03-17 11:59:33 +08006069TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6070 performStylusDrag();
6071
6072 // Move on window and keep button pressed.
6073 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6074 injectMotionEvent(mDispatcher,
6075 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6076 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6077 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6078 .x(50)
6079 .y(50))
6080 .build()))
6081 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6082 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6083 mWindow->consumeDragEvent(false, 50, 50);
6084 mSecondWindow->assertNoEvents();
6085
6086 // Move to another window and release button, expect to drop item.
6087 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6088 injectMotionEvent(mDispatcher,
6089 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6090 .buttonState(0)
6091 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6092 .x(150)
6093 .y(50))
6094 .build()))
6095 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6096 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6097 mWindow->assertNoEvents();
6098 mSecondWindow->assertNoEvents();
6099 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6100
6101 // nothing to the window.
6102 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6103 injectMotionEvent(mDispatcher,
6104 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6105 .buttonState(0)
6106 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6107 .x(150)
6108 .y(50))
6109 .build()))
6110 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6111 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6112 mWindow->assertNoEvents();
6113 mSecondWindow->assertNoEvents();
6114}
6115
Arthur Hung6d0571e2021-04-09 20:18:16 +08006116TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6117 performDrag();
6118
6119 // Set second window invisible.
6120 mSecondWindow->setVisible(false);
6121 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6122
6123 // Move on window.
6124 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6125 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6126 ADISPLAY_ID_DEFAULT, {50, 50}))
6127 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6128 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6129 mWindow->consumeDragEvent(false, 50, 50);
6130 mSecondWindow->assertNoEvents();
6131
6132 // Move to another window.
6133 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6134 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6135 ADISPLAY_ID_DEFAULT, {150, 50}))
6136 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6137 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6138 mWindow->consumeDragEvent(true, 150, 50);
6139 mSecondWindow->assertNoEvents();
6140
6141 // drop to another window.
6142 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6143 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6144 {150, 50}))
6145 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6146 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6147 mFakePolicy->assertDropTargetEquals(nullptr);
6148 mWindow->assertNoEvents();
6149 mSecondWindow->assertNoEvents();
6150}
6151
Vishnu Nair062a8672021-09-03 16:07:44 -07006152class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6153
6154TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6155 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6156 sp<FakeWindowHandle> window =
6157 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6158 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
6159 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6160 window->setFocusable(true);
6161 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6162 setFocusedWindow(window);
6163 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6164
6165 // With the flag set, window should not get any input
6166 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6167 mDispatcher->notifyKey(&keyArgs);
6168 window->assertNoEvents();
6169
6170 NotifyMotionArgs motionArgs =
6171 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6172 ADISPLAY_ID_DEFAULT);
6173 mDispatcher->notifyMotion(&motionArgs);
6174 window->assertNoEvents();
6175
6176 // With the flag cleared, the window should get input
6177 window->setInputFeatures({});
6178 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6179
6180 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6181 mDispatcher->notifyKey(&keyArgs);
6182 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6183
6184 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6185 ADISPLAY_ID_DEFAULT);
6186 mDispatcher->notifyMotion(&motionArgs);
6187 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6188 window->assertNoEvents();
6189}
6190
6191TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6192 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6193 std::make_shared<FakeApplicationHandle>();
6194 sp<FakeWindowHandle> obscuringWindow =
6195 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6196 ADISPLAY_ID_DEFAULT);
6197 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6198 obscuringWindow->setOwnerInfo(111, 111);
6199 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6200 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6201 sp<FakeWindowHandle> window =
6202 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6203 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6204 window->setOwnerInfo(222, 222);
6205 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6206 window->setFocusable(true);
6207 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6208 setFocusedWindow(window);
6209 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6210
6211 // With the flag set, window should not get any input
6212 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6213 mDispatcher->notifyKey(&keyArgs);
6214 window->assertNoEvents();
6215
6216 NotifyMotionArgs motionArgs =
6217 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6218 ADISPLAY_ID_DEFAULT);
6219 mDispatcher->notifyMotion(&motionArgs);
6220 window->assertNoEvents();
6221
6222 // With the flag cleared, the window should get input
6223 window->setInputFeatures({});
6224 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6225
6226 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6227 mDispatcher->notifyKey(&keyArgs);
6228 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6229
6230 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6231 ADISPLAY_ID_DEFAULT);
6232 mDispatcher->notifyMotion(&motionArgs);
6233 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6234 window->assertNoEvents();
6235}
6236
6237TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6238 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6239 std::make_shared<FakeApplicationHandle>();
6240 sp<FakeWindowHandle> obscuringWindow =
6241 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6242 ADISPLAY_ID_DEFAULT);
6243 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6244 obscuringWindow->setOwnerInfo(111, 111);
6245 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6246 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6247 sp<FakeWindowHandle> window =
6248 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6249 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6250 window->setOwnerInfo(222, 222);
6251 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6252 window->setFocusable(true);
6253 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6254 setFocusedWindow(window);
6255 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6256
6257 // With the flag set, window should not get any input
6258 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6259 mDispatcher->notifyKey(&keyArgs);
6260 window->assertNoEvents();
6261
6262 NotifyMotionArgs motionArgs =
6263 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6264 ADISPLAY_ID_DEFAULT);
6265 mDispatcher->notifyMotion(&motionArgs);
6266 window->assertNoEvents();
6267
6268 // When the window is no longer obscured because it went on top, it should get input
6269 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6270
6271 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6272 mDispatcher->notifyKey(&keyArgs);
6273 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6274
6275 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6276 ADISPLAY_ID_DEFAULT);
6277 mDispatcher->notifyMotion(&motionArgs);
6278 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6279 window->assertNoEvents();
6280}
6281
Antonio Kantekf16f2832021-09-28 04:39:20 +00006282class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6283protected:
6284 std::shared_ptr<FakeApplicationHandle> mApp;
6285 sp<FakeWindowHandle> mWindow;
6286 sp<FakeWindowHandle> mSecondWindow;
6287
6288 void SetUp() override {
6289 InputDispatcherTest::SetUp();
6290
6291 mApp = std::make_shared<FakeApplicationHandle>();
6292 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6293 mWindow->setFocusable(true);
6294 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6295 mSecondWindow->setFocusable(true);
6296
6297 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6298 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6299
6300 setFocusedWindow(mWindow);
6301 mWindow->consumeFocusEvent(true);
6302 }
6303
6304 void changeAndVerifyTouchMode(bool inTouchMode) {
6305 mDispatcher->setInTouchMode(inTouchMode);
6306 mWindow->consumeTouchModeEvent(inTouchMode);
6307 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6308 }
6309};
6310
6311TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
6312 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode);
6313}
6314
6315TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
6316 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode);
6317 mWindow->assertNoEvents();
6318 mSecondWindow->assertNoEvents();
6319}
6320
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006321class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6322public:
6323 sp<FakeWindowHandle> createSpy(const Flags<WindowInfo::Flag> flags) {
6324 std::shared_ptr<FakeApplicationHandle> application =
6325 std::make_shared<FakeApplicationHandle>();
6326 std::string name = "Fake Spy ";
6327 name += std::to_string(mSpyCount++);
6328 sp<FakeWindowHandle> spy =
6329 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
6330 spy->setInputFeatures(WindowInfo::Feature::SPY);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006331 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006332 spy->addFlags(flags);
6333 return spy;
6334 }
6335
6336 sp<FakeWindowHandle> createForeground() {
6337 std::shared_ptr<FakeApplicationHandle> application =
6338 std::make_shared<FakeApplicationHandle>();
6339 sp<FakeWindowHandle> window =
6340 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
6341 window->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
6342 return window;
6343 }
6344
6345private:
6346 int mSpyCount{0};
6347};
6348
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006349using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006350/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006351 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6352 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006353TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6354 ScopedSilentDeath _silentDeath;
6355
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006356 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6357 spy->setTrustedOverlay(false);
6358 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6359 ".* not a trusted overlay");
6360}
6361
6362/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006363 * Input injection into a display with a spy window but no foreground windows should succeed.
6364 */
6365TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
6366 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6367 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6368
6369 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6370 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6371 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6372 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6373}
6374
6375/**
6376 * Verify the order in which different input windows receive events. The touched foreground window
6377 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6378 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6379 * receive events before ones belows it.
6380 *
6381 * Here, we set up a scenario with four windows in the following Z order from the top:
6382 * spy1, spy2, window, spy3.
6383 * We then inject an event and verify that the foreground "window" receives it first, followed by
6384 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6385 * window.
6386 */
6387TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6388 auto window = createForeground();
6389 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6390 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6391 auto spy3 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6392 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6393 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6394 const size_t numChannels = channels.size();
6395
6396 base::unique_fd epollFd(epoll_create1(0 /*flags*/));
6397 if (!epollFd.ok()) {
6398 FAIL() << "Failed to create epoll fd";
6399 }
6400
6401 for (size_t i = 0; i < numChannels; i++) {
6402 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6403 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6404 FAIL() << "Failed to add fd to epoll";
6405 }
6406 }
6407
6408 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6409 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6410 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6411
6412 std::vector<size_t> eventOrder;
6413 std::vector<struct epoll_event> events(numChannels);
6414 for (;;) {
6415 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6416 (100ms).count());
6417 if (nFds < 0) {
6418 FAIL() << "Failed to call epoll_wait";
6419 }
6420 if (nFds == 0) {
6421 break; // epoll_wait timed out
6422 }
6423 for (int i = 0; i < nFds; i++) {
6424 ASSERT_EQ(EPOLLIN, events[i].events);
6425 eventOrder.push_back(events[i].data.u64);
6426 channels[i]->consumeMotionDown();
6427 }
6428 }
6429
6430 // Verify the order in which the events were received.
6431 EXPECT_EQ(3u, eventOrder.size());
6432 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6433 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6434 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6435}
6436
6437/**
6438 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6439 */
6440TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6441 auto window = createForeground();
6442 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCHABLE);
6443 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6444
6445 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6446 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6447 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6448 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6449 spy->assertNoEvents();
6450}
6451
6452/**
6453 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6454 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6455 * to the window.
6456 */
6457TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6458 auto window = createForeground();
6459 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6460 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6461 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6462
6463 // Inject an event outside the spy window's touchable region.
6464 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6465 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6466 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6467 window->consumeMotionDown();
6468 spy->assertNoEvents();
6469 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6470 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6471 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6472 window->consumeMotionUp();
6473 spy->assertNoEvents();
6474
6475 // Inject an event inside the spy window's touchable region.
6476 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6477 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6478 {5, 10}))
6479 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6480 window->consumeMotionDown();
6481 spy->consumeMotionDown();
6482}
6483
6484/**
6485 * A spy window that is a modal window will receive gestures outside of its frame and touchable
6486 * region.
6487 */
6488TEST_F(InputDispatcherSpyWindowTest, ModalWindow) {
6489 auto window = createForeground();
6490 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6491 // This spy window does not have the NOT_TOUCH_MODAL flag set.
6492 spy->setFrame(Rect{0, 0, 20, 20});
6493 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6494
6495 // Inject an event outside the spy window's frame and touchable region.
6496 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6497 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6498 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6499 window->consumeMotionDown();
6500 spy->consumeMotionDown();
6501}
6502
6503/**
6504 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
6505 * flag.
6506 */
6507TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6508 auto window = createForeground();
6509 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
6510 spy->setFrame(Rect{0, 0, 20, 20});
6511 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6512
6513 // Inject an event outside the spy window's frame and touchable region.
6514 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6515 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6516 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6517 window->consumeMotionDown();
6518 spy->consumeMotionOutside();
6519}
6520
6521/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006522 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6523 * any other windows - including other spy windows - will also be cancelled.
6524 */
6525TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6526 auto window = createForeground();
6527 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6528 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6529 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6530
6531 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6532 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6533 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6534 window->consumeMotionDown();
6535 spy1->consumeMotionDown();
6536 spy2->consumeMotionDown();
6537
6538 // Pilfer pointers from the second spy window.
6539 mDispatcher->pilferPointers(spy2->getToken());
6540 spy2->assertNoEvents();
6541 spy1->consumeMotionCancel();
6542 window->consumeMotionCancel();
6543
6544 // The rest of the gesture should only be sent to the second spy window.
6545 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6546 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6547 ADISPLAY_ID_DEFAULT))
6548 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6549 spy2->consumeMotionMove();
6550 spy1->assertNoEvents();
6551 window->assertNoEvents();
6552}
6553
6554/**
6555 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6556 * pointers that are down within its bounds.
6557 */
6558TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6559 auto windowLeft = createForeground();
6560 windowLeft->setFrame({0, 0, 100, 200});
6561 auto windowRight = createForeground();
6562 windowRight->setFrame({100, 0, 200, 200});
6563 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6564 spy->setFrame({0, 0, 200, 200});
6565 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6566
6567 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6568 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6569 {50, 50}))
6570 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6571 windowLeft->consumeMotionDown();
6572 spy->consumeMotionDown();
6573
6574 const MotionEvent secondFingerDownEvent =
6575 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6576 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6577 AINPUT_SOURCE_TOUCHSCREEN)
6578 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6579 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6580 .pointer(
6581 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6582 .build();
6583 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6584 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6585 InputEventInjectionSync::WAIT_FOR_RESULT))
6586 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6587 windowRight->consumeMotionDown();
6588 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6589}
6590
6591/**
6592 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6593 * the spy should receive the second pointer with ACTION_DOWN.
6594 */
6595TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6596 auto window = createForeground();
6597 window->setFrame({0, 0, 200, 200});
6598 auto spyRight = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6599 spyRight->setFrame({100, 0, 200, 200});
6600 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6601
6602 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6603 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6604 {50, 50}))
6605 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6606 window->consumeMotionDown();
6607 spyRight->assertNoEvents();
6608
6609 const MotionEvent secondFingerDownEvent =
6610 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6611 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6612 AINPUT_SOURCE_TOUCHSCREEN)
6613 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6614 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6615 .pointer(
6616 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6617 .build();
6618 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6619 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6620 InputEventInjectionSync::WAIT_FOR_RESULT))
6621 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6622 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6623 spyRight->consumeMotionDown();
6624}
6625
Prabir Pradhand65552b2021-10-07 11:23:50 -07006626class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6627public:
6628 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6629 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6630 std::make_shared<FakeApplicationHandle>();
6631 sp<FakeWindowHandle> overlay =
6632 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6633 ADISPLAY_ID_DEFAULT);
6634 overlay->setFocusable(false);
6635 overlay->setOwnerInfo(111, 111);
6636 overlay->setFlags(WindowInfo::Flag::NOT_TOUCHABLE | WindowInfo::Flag::SPLIT_TOUCH);
6637 overlay->setInputFeatures(WindowInfo::Feature::INTERCEPTS_STYLUS);
6638 overlay->setTrustedOverlay(true);
6639
6640 std::shared_ptr<FakeApplicationHandle> application =
6641 std::make_shared<FakeApplicationHandle>();
6642 sp<FakeWindowHandle> window =
6643 new FakeWindowHandle(application, mDispatcher, "Application window",
6644 ADISPLAY_ID_DEFAULT);
6645 window->setFocusable(true);
6646 window->setOwnerInfo(222, 222);
6647 window->setFlags(WindowInfo::Flag::SPLIT_TOUCH);
6648
6649 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6650 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6651 setFocusedWindow(window);
6652 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6653 return {std::move(overlay), std::move(window)};
6654 }
6655
6656 void sendFingerEvent(int32_t action) {
6657 NotifyMotionArgs motionArgs =
6658 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6659 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6660 mDispatcher->notifyMotion(&motionArgs);
6661 }
6662
6663 void sendStylusEvent(int32_t action) {
6664 NotifyMotionArgs motionArgs =
6665 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6666 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6667 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6668 mDispatcher->notifyMotion(&motionArgs);
6669 }
6670};
6671
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006672using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
6673
6674TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
6675 ScopedSilentDeath _silentDeath;
6676
Prabir Pradhand65552b2021-10-07 11:23:50 -07006677 auto [overlay, window] = setupStylusOverlayScenario();
6678 overlay->setTrustedOverlay(false);
6679 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6680 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6681 ".* not a trusted overlay");
6682}
6683
6684TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6685 auto [overlay, window] = setupStylusOverlayScenario();
6686 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6687
6688 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6689 overlay->consumeMotionDown();
6690 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6691 overlay->consumeMotionUp();
6692
6693 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6694 window->consumeMotionDown();
6695 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6696 window->consumeMotionUp();
6697
6698 overlay->assertNoEvents();
6699 window->assertNoEvents();
6700}
6701
6702TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6703 auto [overlay, window] = setupStylusOverlayScenario();
6704 overlay->setInputFeatures(overlay->getInfo()->inputFeatures | WindowInfo::Feature::SPY);
6705 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6706
6707 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6708 overlay->consumeMotionDown();
6709 window->consumeMotionDown();
6710 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6711 overlay->consumeMotionUp();
6712 window->consumeMotionUp();
6713
6714 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6715 window->consumeMotionDown();
6716 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6717 window->consumeMotionUp();
6718
6719 overlay->assertNoEvents();
6720 window->assertNoEvents();
6721}
6722
Garfield Tane84e6f92019-08-29 17:28:41 -07006723} // namespace android::inputdispatcher