blob: e00ce420f1b0b0184c0c9155ded387fcdd006f00 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Garfield Tan0fc2fa72019-08-29 17:22:15 -070017#include "../dispatcher/InputDispatcher.h"
Michael Wrightd02c5b62014-02-10 15:10:22 -080018
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -070019#include <android-base/properties.h>
Prabir Pradhana3ab87a2022-01-27 10:00:21 -080020#include <android-base/silent_death_test.h>
Garfield Tan1c7bc862020-01-28 13:24:04 -080021#include <android-base/stringprintf.h>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070022#include <android-base/thread_annotations.h>
Robert Carr803535b2018-08-02 16:38:15 -070023#include <binder/Binder.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080024#include <gtest/gtest.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100025#include <input/Input.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080026#include <linux/input.h>
Prabir Pradhan07e05b62021-11-19 03:57:24 -080027#include <sys/epoll.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100028
Garfield Tan1c7bc862020-01-28 13:24:04 -080029#include <cinttypes>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070030#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080031#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080032#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080033
Garfield Tan1c7bc862020-01-28 13:24:04 -080034using android::base::StringPrintf;
chaviw3277faf2021-05-19 16:45:23 -050035using android::gui::FocusRequest;
36using android::gui::TouchOcclusionMode;
37using android::gui::WindowInfo;
38using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080039using android::os::InputEventInjectionResult;
40using android::os::InputEventInjectionSync;
Michael Wright44753b12020-07-08 13:48:11 +010041using namespace android::flag_operators;
Garfield Tan1c7bc862020-01-28 13:24:04 -080042
Garfield Tane84e6f92019-08-29 17:28:41 -070043namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080044
45// An arbitrary time value.
46static const nsecs_t ARBITRARY_TIME = 1234;
47
48// An arbitrary device id.
49static const int32_t DEVICE_ID = 1;
50
Jeff Brownf086ddb2014-02-11 14:28:48 -080051// An arbitrary display id.
Arthur Hungabbb9d82021-09-01 14:52:30 +000052static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
53static constexpr int32_t SECOND_DISPLAY_ID = 1;
Jeff Brownf086ddb2014-02-11 14:28:48 -080054
Michael Wrightd02c5b62014-02-10 15:10:22 -080055// An arbitrary injector pid / uid pair that has permission to inject events.
56static const int32_t INJECTOR_PID = 999;
57static const int32_t INJECTOR_UID = 1001;
58
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000059// An arbitrary pid of the gesture monitor window
60static constexpr int32_t MONITOR_PID = 2001;
61
chaviwd1c23182019-12-20 18:44:56 -080062struct PointF {
63 float x;
64 float y;
65};
Michael Wrightd02c5b62014-02-10 15:10:22 -080066
Gang Wang342c9272020-01-13 13:15:04 -050067/**
68 * Return a DOWN key event with KEYCODE_A.
69 */
70static KeyEvent getTestKeyEvent() {
71 KeyEvent event;
72
Garfield Tanfbe732e2020-01-24 11:26:14 -080073 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
74 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
75 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050076 return event;
77}
78
Siarhei Vishniakouca205502021-07-16 21:31:58 +000079static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
80 ASSERT_EQ(expectedAction, receivedAction)
81 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
82 << MotionEvent::actionToString(receivedAction);
83}
84
Michael Wrightd02c5b62014-02-10 15:10:22 -080085// --- FakeInputDispatcherPolicy ---
86
87class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
88 InputDispatcherConfiguration mConfig;
89
90protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100091 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -080092
93public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100094 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +080095
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080096 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -070097 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
98 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
99 EXPECT_EQ(event.getDisplayId(), args.displayId);
100
101 const auto& keyEvent = static_cast<const KeyEvent&>(event);
102 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
103 EXPECT_EQ(keyEvent.getAction(), args.action);
104 });
Jackal Guof9696682018-10-05 12:23:23 +0800105 }
106
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700107 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
108 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
109 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
110 EXPECT_EQ(event.getDisplayId(), args.displayId);
111
112 const auto& motionEvent = static_cast<const MotionEvent&>(event);
113 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
114 EXPECT_EQ(motionEvent.getAction(), args.action);
115 EXPECT_EQ(motionEvent.getX(0), point.x);
116 EXPECT_EQ(motionEvent.getY(0), point.y);
117 EXPECT_EQ(motionEvent.getRawX(0), point.x);
118 EXPECT_EQ(motionEvent.getRawY(0), point.y);
119 });
Jackal Guof9696682018-10-05 12:23:23 +0800120 }
121
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700122 void assertFilterInputEventWasNotCalled() {
123 std::scoped_lock lock(mLock);
124 ASSERT_EQ(nullptr, mFilteredEvent);
125 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800126
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800127 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700128 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800129 ASSERT_TRUE(mConfigurationChangedTime)
130 << "Timed out waiting for configuration changed call";
131 ASSERT_EQ(*mConfigurationChangedTime, when);
132 mConfigurationChangedTime = std::nullopt;
133 }
134
135 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700136 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800137 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800138 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800139 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
140 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
141 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
142 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
143 mLastNotifySwitch = std::nullopt;
144 }
145
chaviwfd6d3512019-03-25 13:23:49 -0700146 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700147 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800148 ASSERT_EQ(touchedToken, mOnPointerDownToken);
149 mOnPointerDownToken.clear();
150 }
151
152 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700153 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800154 ASSERT_TRUE(mOnPointerDownToken == nullptr)
155 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700156 }
157
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700158 // This function must be called soon after the expected ANR timer starts,
159 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500160 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700161 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500162 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
163 std::shared_ptr<InputApplicationHandle> application;
164 { // acquire lock
165 std::unique_lock lock(mLock);
166 android::base::ScopedLockAssertion assumeLocked(mLock);
167 ASSERT_NO_FATAL_FAILURE(
168 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
169 } // release lock
170 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700171 }
172
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000173 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
174 const sp<IBinder>& expectedConnectionToken) {
175 sp<IBinder> connectionToken = getUnresponsiveWindowToken(timeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500176 ASSERT_EQ(expectedConnectionToken, connectionToken);
177 }
178
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000179 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
180 sp<IBinder> connectionToken = getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500181 ASSERT_EQ(expectedConnectionToken, connectionToken);
182 }
183
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000184 void assertNotifyMonitorUnresponsiveWasCalled(std::chrono::nanoseconds timeout) {
185 int32_t pid = getUnresponsiveMonitorPid(timeout);
186 ASSERT_EQ(MONITOR_PID, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500187 }
188
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000189 void assertNotifyMonitorResponsiveWasCalled() {
190 int32_t pid = getResponsiveMonitorPid();
191 ASSERT_EQ(MONITOR_PID, pid);
192 }
193
194 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500195 std::unique_lock lock(mLock);
196 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000197 return getAnrTokenLockedInterruptible(timeout, mAnrWindowTokens, lock);
198 }
199
200 sp<IBinder> getResponsiveWindowToken() {
201 std::unique_lock lock(mLock);
202 android::base::ScopedLockAssertion assumeLocked(mLock);
203 return getAnrTokenLockedInterruptible(0s, mResponsiveWindowTokens, lock);
204 }
205
206 int32_t getUnresponsiveMonitorPid(std::chrono::nanoseconds timeout) {
207 std::unique_lock lock(mLock);
208 android::base::ScopedLockAssertion assumeLocked(mLock);
209 return getAnrTokenLockedInterruptible(timeout, mAnrMonitorPids, lock);
210 }
211
212 int32_t getResponsiveMonitorPid() {
213 std::unique_lock lock(mLock);
214 android::base::ScopedLockAssertion assumeLocked(mLock);
215 return getAnrTokenLockedInterruptible(0s, mResponsiveMonitorPids, lock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500216 }
217
218 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
219 // for a specific container to become non-empty. When the container is non-empty, return the
220 // first entry from the container and erase it.
221 template <class T>
222 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
223 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700224 // If there is an ANR, Dispatcher won't be idle because there are still events
225 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
226 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500227 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
228 // to provide it some time to act. 100ms seems reasonable.
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800229 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
230 const std::chrono::time_point start = std::chrono::steady_clock::now();
231 std::optional<T> token =
232 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
233 if (!token.has_value()) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500234 ADD_FAILURE() << "Did not receive the ANR callback";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000235 return {};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700236 }
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800237
238 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700239 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
240 // the dispatcher started counting before this function was called
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700241 if (std::chrono::abs(timeout - waited) > 100ms) {
242 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
243 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
244 << "ms, but waited "
245 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
246 << "ms instead";
247 }
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800248 return *token;
249 }
250
251 template <class T>
252 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
253 std::queue<T>& storage,
254 std::unique_lock<std::mutex>& lock,
255 std::condition_variable& condition)
256 REQUIRES(mLock) {
257 condition.wait_for(lock, timeout,
258 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
259 if (storage.empty()) {
260 ADD_FAILURE() << "Did not receive the expected callback";
261 return std::nullopt;
262 }
263 T item = storage.front();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500264 storage.pop();
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800265 return std::make_optional(item);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700266 }
267
268 void assertNotifyAnrWasNotCalled() {
269 std::scoped_lock lock(mLock);
270 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000271 ASSERT_TRUE(mAnrWindowTokens.empty());
272 ASSERT_TRUE(mAnrMonitorPids.empty());
273 ASSERT_TRUE(mResponsiveWindowTokens.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500274 << "ANR was not called, but please also consume the 'connection is responsive' "
275 "signal";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000276 ASSERT_TRUE(mResponsiveMonitorPids.empty())
277 << "Monitor ANR was not called, but please also consume the 'monitor is responsive'"
278 " signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700279 }
280
Garfield Tan1c7bc862020-01-28 13:24:04 -0800281 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
282 mConfig.keyRepeatTimeout = timeout;
283 mConfig.keyRepeatDelay = delay;
284 }
285
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000286 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800287 std::unique_lock lock(mLock);
288 base::ScopedLockAssertion assumeLocked(mLock);
289
290 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
291 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000292 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800293 enabled;
294 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000295 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
296 << ") to be called.";
297 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800298 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000299 auto request = *mPointerCaptureRequest;
300 mPointerCaptureRequest.reset();
301 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800302 }
303
304 void assertSetPointerCaptureNotCalled() {
305 std::unique_lock lock(mLock);
306 base::ScopedLockAssertion assumeLocked(mLock);
307
308 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000309 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800310 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000311 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800312 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000313 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800314 }
315
arthurhungf452d0b2021-01-06 00:19:52 +0800316 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
317 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800318 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800319 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800320 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800321 }
322
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800323 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
324 std::unique_lock lock(mLock);
325 base::ScopedLockAssertion assumeLocked(mLock);
326 std::optional<sp<IBinder>> receivedToken =
327 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
328 mNotifyInputChannelBroken);
329 ASSERT_TRUE(receivedToken.has_value());
330 ASSERT_EQ(token, *receivedToken);
331 }
332
Michael Wrightd02c5b62014-02-10 15:10:22 -0800333private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700334 std::mutex mLock;
335 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
336 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
337 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
338 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800339
Prabir Pradhan99987712020-11-10 18:43:05 -0800340 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000341
342 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800343
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700344 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700345 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000346 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
347 std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
348 std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
349 std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700350 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800351 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
352 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700353
arthurhungf452d0b2021-01-06 00:19:52 +0800354 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800355 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800356
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600357 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700358 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800359 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800360 }
361
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000362 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700363 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000364 mAnrWindowTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700365 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500366 }
367
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000368 void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500369 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000370 mAnrMonitorPids.push(pid);
371 mNotifyAnr.notify_all();
372 }
373
374 void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
375 std::scoped_lock lock(mLock);
376 mResponsiveWindowTokens.push(connectionToken);
377 mNotifyAnr.notify_all();
378 }
379
380 void notifyMonitorResponsive(int32_t pid) override {
381 std::scoped_lock lock(mLock);
382 mResponsiveMonitorPids.push(pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500383 mNotifyAnr.notify_all();
384 }
385
386 void notifyNoFocusedWindowAnr(
387 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
388 std::scoped_lock lock(mLock);
389 mAnrApplications.push(applicationHandle);
390 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800391 }
392
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800393 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
394 std::scoped_lock lock(mLock);
395 mBrokenInputChannels.push(connectionToken);
396 mNotifyInputChannelBroken.notify_all();
397 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800398
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600399 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700400
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600401 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700402 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
403 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
404 const std::vector<float>& values) override {}
405
406 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
407 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000408
Chris Yefb552902021-02-03 17:18:37 -0800409 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
410
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600411 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800412 *outConfig = mConfig;
413 }
414
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600415 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700416 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800417 switch (inputEvent->getType()) {
418 case AINPUT_EVENT_TYPE_KEY: {
419 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800420 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800421 break;
422 }
423
424 case AINPUT_EVENT_TYPE_MOTION: {
425 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800426 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800427 break;
428 }
429 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800430 return true;
431 }
432
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600433 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800434
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600435 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800436
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600437 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800438 return 0;
439 }
440
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600441 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800442 return false;
443 }
444
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600445 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
446 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700447 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800448 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
449 * essentially a passthrough for notifySwitch.
450 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800451 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800452 }
453
Sean Stoutb4e0a592021-02-23 07:34:53 -0800454 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800455
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800456 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
457 return pid == INJECTOR_PID && uid == INJECTOR_UID;
458 }
Jackal Guof9696682018-10-05 12:23:23 +0800459
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600460 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700461 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700462 mOnPointerDownToken = newToken;
463 }
464
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000465 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800466 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000467 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800468 mPointerCaptureChangedCondition.notify_all();
469 }
470
arthurhungf452d0b2021-01-06 00:19:52 +0800471 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
472 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800473 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800474 mDropTargetWindowToken = token;
475 }
476
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700477 void assertFilterInputEventWasCalledInternal(
478 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700479 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800480 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700481 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800482 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800484};
485
Michael Wrightd02c5b62014-02-10 15:10:22 -0800486// --- InputDispatcherTest ---
487
488class InputDispatcherTest : public testing::Test {
489protected:
490 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700491 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800492
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000493 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800494 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700495 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800496 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000497 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700498 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800499 }
500
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000501 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700502 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800503 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700504 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800505 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700506
507 /**
508 * Used for debugging when writing the test
509 */
510 void dumpDispatcherState() {
511 std::string dump;
512 mDispatcher->dump(dump);
513 std::stringstream ss(dump);
514 std::string to;
515
516 while (std::getline(ss, to, '\n')) {
517 ALOGE("%s", to.c_str());
518 }
519 }
Vishnu Nair958da932020-08-21 17:12:37 -0700520
chaviw3277faf2021-05-19 16:45:23 -0500521 void setFocusedWindow(const sp<WindowInfoHandle>& window,
522 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700523 FocusRequest request;
524 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000525 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700526 if (focusedWindow) {
527 request.focusedToken = focusedWindow->getToken();
528 }
529 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
530 request.displayId = window->getInfo()->displayId;
531 mDispatcher->setFocusedWindow(request);
532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800533};
534
Michael Wrightd02c5b62014-02-10 15:10:22 -0800535TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
536 KeyEvent event;
537
538 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800539 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
540 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600541 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
542 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800543 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700544 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800545 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800546 << "Should reject key events with undefined action.";
547
548 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800549 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
550 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600551 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800552 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700553 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800554 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800555 << "Should reject key events with ACTION_MULTIPLE.";
556}
557
558TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
559 MotionEvent event;
560 PointerProperties pointerProperties[MAX_POINTERS + 1];
561 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800562 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563 pointerProperties[i].clear();
564 pointerProperties[i].id = i;
565 pointerCoords[i].clear();
566 }
567
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800568 // Some constants commonly used below
569 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
570 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
571 constexpr int32_t metaState = AMETA_NONE;
572 constexpr MotionClassification classification = MotionClassification::NONE;
573
chaviw9eaa22c2020-07-01 16:21:27 -0700574 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800575 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800576 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700577 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
578 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700579 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
580 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700581 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800582 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700583 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800584 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800585 << "Should reject motion events with undefined action.";
586
587 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800588 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700589 AMOTION_EVENT_ACTION_POINTER_DOWN |
590 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700591 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
592 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700593 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500594 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800595 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700596 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800597 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800598 << "Should reject motion events with pointer down index too large.";
599
Garfield Tanfbe732e2020-01-24 11:26:14 -0800600 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700601 AMOTION_EVENT_ACTION_POINTER_DOWN |
602 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700603 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
604 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700605 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500606 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800607 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700608 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800609 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800610 << "Should reject motion events with pointer down index too small.";
611
612 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800613 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700614 AMOTION_EVENT_ACTION_POINTER_UP |
615 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700616 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
617 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700618 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500619 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800620 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700621 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800622 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800623 << "Should reject motion events with pointer up index too large.";
624
Garfield Tanfbe732e2020-01-24 11:26:14 -0800625 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700626 AMOTION_EVENT_ACTION_POINTER_UP |
627 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700628 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
629 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700630 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500631 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800632 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700633 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800634 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800635 << "Should reject motion events with pointer up index too small.";
636
637 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800638 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
639 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700640 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700641 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
642 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700643 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800644 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700645 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800646 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800647 << "Should reject motion events with 0 pointers.";
648
Garfield Tanfbe732e2020-01-24 11:26:14 -0800649 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
650 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700651 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700652 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
653 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700654 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800655 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700656 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800657 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800658 << "Should reject motion events with more than MAX_POINTERS pointers.";
659
660 // Rejects motion events with invalid pointer ids.
661 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800662 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
663 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700664 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700665 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
666 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700667 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800668 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700669 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800670 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800671 << "Should reject motion events with pointer ids less than 0.";
672
673 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800674 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
675 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700676 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700677 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
678 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700679 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800680 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700681 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800682 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800683 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
684
685 // Rejects motion events with duplicate pointer ids.
686 pointerProperties[0].id = 1;
687 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800688 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
689 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700690 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700691 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
692 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700693 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800694 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700695 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800696 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800697 << "Should reject motion events with duplicate pointer ids.";
698}
699
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800700/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
701
702TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
703 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800704 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800705 mDispatcher->notifyConfigurationChanged(&args);
706 ASSERT_TRUE(mDispatcher->waitForIdle());
707
708 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
709}
710
711TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800712 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
713 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800714 mDispatcher->notifySwitch(&args);
715
716 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
717 args.policyFlags |= POLICY_FLAG_TRUSTED;
718 mFakePolicy->assertNotifySwitchWasCalled(args);
719}
720
Arthur Hungb92218b2018-08-14 12:00:21 +0800721// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700722static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700723// Default input dispatching timeout if there is no focused application or paused window
724// from which to determine an appropriate dispatching timeout.
725static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
726 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
727 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800728
729class FakeApplicationHandle : public InputApplicationHandle {
730public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700731 FakeApplicationHandle() {
732 mInfo.name = "Fake Application";
733 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500734 mInfo.dispatchingTimeoutMillis =
735 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700736 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800737 virtual ~FakeApplicationHandle() {}
738
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000739 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700740
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500741 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
742 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700743 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800744};
745
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800746class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800747public:
Garfield Tan15601662020-09-22 15:32:38 -0700748 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800749 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700750 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800751 }
752
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800753 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700754 InputEvent* event;
755 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
756 if (!consumeSeq) {
757 return nullptr;
758 }
759 finishEvent(*consumeSeq);
760 return event;
761 }
762
763 /**
764 * Receive an event without acknowledging it.
765 * Return the sequence number that could later be used to send finished signal.
766 */
767 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800768 uint32_t consumeSeq;
769 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800770
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800771 std::chrono::time_point start = std::chrono::steady_clock::now();
772 status_t status = WOULD_BLOCK;
773 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800774 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800775 &event);
776 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
777 if (elapsed > 100ms) {
778 break;
779 }
780 }
781
782 if (status == WOULD_BLOCK) {
783 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700784 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800785 }
786
787 if (status != OK) {
788 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700789 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800790 }
791 if (event == nullptr) {
792 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700793 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800794 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700795 if (outEvent != nullptr) {
796 *outEvent = event;
797 }
798 return consumeSeq;
799 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800800
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700801 /**
802 * To be used together with "receiveEvent" to complete the consumption of an event.
803 */
804 void finishEvent(uint32_t consumeSeq) {
805 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
806 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800807 }
808
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000809 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
810 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
811 ASSERT_EQ(OK, status);
812 }
813
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000814 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
815 std::optional<int32_t> expectedDisplayId,
816 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800817 InputEvent* event = consume();
818
819 ASSERT_NE(nullptr, event) << mName.c_str()
820 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800821 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700822 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800823 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800824
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000825 if (expectedDisplayId.has_value()) {
826 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
827 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800828
Tiger Huang8664f8c2018-10-11 19:14:35 +0800829 switch (expectedEventType) {
830 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800831 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
832 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000833 if (expectedFlags.has_value()) {
834 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
835 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800836 break;
837 }
838 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800839 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000840 assertMotionAction(expectedAction, motionEvent.getAction());
841
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000842 if (expectedFlags.has_value()) {
843 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
844 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800845 break;
846 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100847 case AINPUT_EVENT_TYPE_FOCUS: {
848 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
849 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800850 case AINPUT_EVENT_TYPE_CAPTURE: {
851 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
852 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000853 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
854 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
855 }
arthurhungb89ccb02020-12-30 16:19:01 +0800856 case AINPUT_EVENT_TYPE_DRAG: {
857 FAIL() << "Use 'consumeDragEvent' for DRAG events";
858 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800859 default: {
860 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
861 }
862 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800863 }
864
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100865 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
866 InputEvent* event = consume();
867 ASSERT_NE(nullptr, event) << mName.c_str()
868 << ": consumer should have returned non-NULL event.";
869 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
870 << "Got " << inputEventTypeToString(event->getType())
871 << " event instead of FOCUS event";
872
873 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
874 << mName.c_str() << ": event displayId should always be NONE.";
875
876 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
877 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100878 }
879
Prabir Pradhan99987712020-11-10 18:43:05 -0800880 void consumeCaptureEvent(bool hasCapture) {
881 const InputEvent* event = consume();
882 ASSERT_NE(nullptr, event) << mName.c_str()
883 << ": consumer should have returned non-NULL event.";
884 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
885 << "Got " << inputEventTypeToString(event->getType())
886 << " event instead of CAPTURE event";
887
888 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
889 << mName.c_str() << ": event displayId should always be NONE.";
890
891 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
892 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
893 }
894
arthurhungb89ccb02020-12-30 16:19:01 +0800895 void consumeDragEvent(bool isExiting, float x, float y) {
896 const InputEvent* event = consume();
897 ASSERT_NE(nullptr, event) << mName.c_str()
898 << ": consumer should have returned non-NULL event.";
899 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
900 << "Got " << inputEventTypeToString(event->getType())
901 << " event instead of DRAG event";
902
903 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
904 << mName.c_str() << ": event displayId should always be NONE.";
905
906 const auto& dragEvent = static_cast<const DragEvent&>(*event);
907 EXPECT_EQ(isExiting, dragEvent.isExiting());
908 EXPECT_EQ(x, dragEvent.getX());
909 EXPECT_EQ(y, dragEvent.getY());
910 }
911
Antonio Kantekf16f2832021-09-28 04:39:20 +0000912 void consumeTouchModeEvent(bool inTouchMode) {
913 const InputEvent* event = consume();
914 ASSERT_NE(nullptr, event) << mName.c_str()
915 << ": consumer should have returned non-NULL event.";
916 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
917 << "Got " << inputEventTypeToString(event->getType())
918 << " event instead of TOUCH_MODE event";
919
920 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
921 << mName.c_str() << ": event displayId should always be NONE.";
922 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
923 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
924 }
925
chaviwd1c23182019-12-20 18:44:56 -0800926 void assertNoEvents() {
927 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700928 if (event == nullptr) {
929 return;
930 }
931 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
932 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
933 ADD_FAILURE() << "Received key event "
934 << KeyEvent::actionToString(keyEvent.getAction());
935 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
936 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
937 ADD_FAILURE() << "Received motion event "
938 << MotionEvent::actionToString(motionEvent.getAction());
939 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
940 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
941 ADD_FAILURE() << "Received focus event, hasFocus = "
942 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800943 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
944 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
945 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
946 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000947 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
948 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
949 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
950 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700951 }
952 FAIL() << mName.c_str()
953 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800954 }
955
956 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
957
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800958 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
959
chaviwd1c23182019-12-20 18:44:56 -0800960protected:
961 std::unique_ptr<InputConsumer> mConsumer;
962 PreallocatedInputEventFactory mEventFactory;
963
964 std::string mName;
965};
966
chaviw3277faf2021-05-19 16:45:23 -0500967class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800968public:
969 static const int32_t WIDTH = 600;
970 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800971
Chris Yea209fde2020-07-22 13:54:51 -0700972 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700973 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500974 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800975 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500976 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700977 base::Result<std::unique_ptr<InputChannel>> channel =
978 dispatcher->createInputChannel(name);
979 token = (*channel)->getConnectionToken();
980 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800981 }
982
983 inputApplicationHandle->updateInfo();
984 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
985
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500986 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700987 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800988 mInfo.name = name;
chaviw3277faf2021-05-19 16:45:23 -0500989 mInfo.type = WindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500990 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000991 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800992 mInfo.frameLeft = 0;
993 mInfo.frameTop = 0;
994 mInfo.frameRight = WIDTH;
995 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700996 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800997 mInfo.globalScaleFactor = 1.0;
998 mInfo.touchableRegion.clear();
999 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
1000 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -07001001 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -08001002 mInfo.hasWallpaper = false;
1003 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -08001004 mInfo.ownerPid = INJECTOR_PID;
1005 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -08001006 mInfo.displayId = displayId;
Prabir Pradhand65552b2021-10-07 11:23:50 -07001007 mInfo.trustedOverlay = false;
chaviwd1c23182019-12-20 18:44:56 -08001008 }
1009
Arthur Hungabbb9d82021-09-01 14:52:30 +00001010 sp<FakeWindowHandle> clone(
1011 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001012 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001013 sp<FakeWindowHandle> handle =
1014 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1015 displayId, mInfo.token);
1016 return handle;
1017 }
1018
Vishnu Nair47074b82020-08-14 11:54:47 -07001019 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -08001020
Vishnu Nair958da932020-08-21 17:12:37 -07001021 void setVisible(bool visible) { mInfo.visible = visible; }
1022
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001023 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001024 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001025 }
1026
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001027 void setPaused(bool paused) { mInfo.paused = paused; }
1028
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001029 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1030
chaviw3277faf2021-05-19 16:45:23 -05001031 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001032
Bernardo Rufino7393d172021-02-26 13:56:11 +00001033 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1034
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001035 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001036 mInfo.frameLeft = frame.left;
1037 mInfo.frameTop = frame.top;
1038 mInfo.frameRight = frame.right;
1039 mInfo.frameBottom = frame.bottom;
1040 mInfo.touchableRegion.clear();
1041 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001042
1043 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1044 ui::Transform translate;
1045 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1046 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001047 }
1048
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001049 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1050
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001051 void setType(WindowInfo::Type type) { mInfo.type = type; }
1052
1053 void setHasWallpaper(bool hasWallpaper) { mInfo.hasWallpaper = hasWallpaper; }
1054
chaviw3277faf2021-05-19 16:45:23 -05001055 void addFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags |= flags; }
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00001056
chaviw3277faf2021-05-19 16:45:23 -05001057 void setFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -08001058
Prabir Pradhand65552b2021-10-07 11:23:50 -07001059 void setInputFeatures(Flags<WindowInfo::Feature> features) { mInfo.inputFeatures = features; }
1060
1061 void setTrustedOverlay(bool trustedOverlay) { mInfo.trustedOverlay = trustedOverlay; }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001062
chaviw9eaa22c2020-07-01 16:21:27 -07001063 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1064 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1065 }
1066
1067 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001068
yunho.shinf4a80b82020-11-16 21:13:57 +09001069 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1070
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001071 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1072 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1073 expectedFlags);
1074 }
1075
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001076 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1077 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1078 }
1079
Svet Ganov5d3bc372020-01-26 23:11:07 -08001080 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001081 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001082 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1083 expectedFlags);
1084 }
1085
1086 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001087 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001088 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1089 expectedFlags);
1090 }
1091
1092 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001093 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001094 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1095 }
1096
1097 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1098 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001099 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1100 expectedFlags);
1101 }
1102
Svet Ganov5d3bc372020-01-26 23:11:07 -08001103 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001104 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1105 int32_t expectedFlags = 0) {
1106 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1107 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001108 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1109 }
1110
1111 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001112 int32_t expectedFlags = 0) {
1113 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1114 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001115 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1116 }
1117
1118 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001119 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001120 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1121 expectedFlags);
1122 }
1123
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001124 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1125 int32_t expectedFlags = 0) {
1126 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1127 expectedFlags);
1128 }
1129
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001130 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1131 int32_t expectedFlags = 0) {
1132 InputEvent* event = consume();
1133 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1134 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1135 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1136 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1137 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1138 }
1139
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001140 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1141 ASSERT_NE(mInputReceiver, nullptr)
1142 << "Cannot consume events from a window with no receiver";
1143 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1144 }
1145
Prabir Pradhan99987712020-11-10 18:43:05 -08001146 void consumeCaptureEvent(bool hasCapture) {
1147 ASSERT_NE(mInputReceiver, nullptr)
1148 << "Cannot consume events from a window with no receiver";
1149 mInputReceiver->consumeCaptureEvent(hasCapture);
1150 }
1151
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001152 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1153 std::optional<int32_t> expectedDisplayId,
1154 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001155 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1156 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1157 expectedFlags);
1158 }
1159
arthurhungb89ccb02020-12-30 16:19:01 +08001160 void consumeDragEvent(bool isExiting, float x, float y) {
1161 mInputReceiver->consumeDragEvent(isExiting, x, y);
1162 }
1163
Antonio Kantekf16f2832021-09-28 04:39:20 +00001164 void consumeTouchModeEvent(bool inTouchMode) {
1165 ASSERT_NE(mInputReceiver, nullptr)
1166 << "Cannot consume events from a window with no receiver";
1167 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1168 }
1169
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001170 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001171 if (mInputReceiver == nullptr) {
1172 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1173 return std::nullopt;
1174 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001175 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001176 }
1177
1178 void finishEvent(uint32_t sequenceNum) {
1179 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1180 mInputReceiver->finishEvent(sequenceNum);
1181 }
1182
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001183 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1184 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1185 mInputReceiver->sendTimeline(inputEventId, timeline);
1186 }
1187
chaviwaf87b3e2019-10-01 16:59:28 -07001188 InputEvent* consume() {
1189 if (mInputReceiver == nullptr) {
1190 return nullptr;
1191 }
1192 return mInputReceiver->consume();
1193 }
1194
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001195 MotionEvent* consumeMotion() {
1196 InputEvent* event = consume();
1197 if (event == nullptr) {
1198 ADD_FAILURE() << "Consume failed : no event";
1199 return nullptr;
1200 }
1201 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1202 ADD_FAILURE() << "Instead of motion event, got "
1203 << inputEventTypeToString(event->getType());
1204 return nullptr;
1205 }
1206 return static_cast<MotionEvent*>(event);
1207 }
1208
Arthur Hungb92218b2018-08-14 12:00:21 +08001209 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001210 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001211 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001212 return; // Can't receive events if the window does not have input channel
1213 }
1214 ASSERT_NE(nullptr, mInputReceiver)
1215 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001216 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001217 }
1218
chaviwaf87b3e2019-10-01 16:59:28 -07001219 sp<IBinder> getToken() { return mInfo.token; }
1220
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001221 const std::string& getName() { return mName; }
1222
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001223 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1224 mInfo.ownerPid = ownerPid;
1225 mInfo.ownerUid = ownerUid;
1226 }
1227
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001228 void destroyReceiver() { mInputReceiver = nullptr; }
1229
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001230 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1231
chaviwd1c23182019-12-20 18:44:56 -08001232private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001233 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001234 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001235 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001236};
1237
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001238std::atomic<int32_t> FakeWindowHandle::sId{1};
1239
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001240static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001241 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001242 int32_t displayId = ADISPLAY_ID_NONE,
1243 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001244 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1245 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001246 KeyEvent event;
1247 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1248
1249 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001250 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001251 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1252 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001253
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001254 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1255 if (!allowKeyRepeat) {
1256 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1257 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001258 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001259 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001260 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001261}
1262
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001263static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001264 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001265 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1266}
1267
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001268// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1269// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1270// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001271static InputEventInjectionResult injectKeyDownNoRepeat(
1272 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001273 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1274 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1275 /* allowKeyRepeat */ false);
1276}
1277
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001278static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001279 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001280 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1281}
1282
Garfield Tandf26e862020-07-01 20:18:19 -07001283class PointerBuilder {
1284public:
1285 PointerBuilder(int32_t id, int32_t toolType) {
1286 mProperties.clear();
1287 mProperties.id = id;
1288 mProperties.toolType = toolType;
1289 mCoords.clear();
1290 }
1291
1292 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1293
1294 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1295
1296 PointerBuilder& axis(int32_t axis, float value) {
1297 mCoords.setAxisValue(axis, value);
1298 return *this;
1299 }
1300
1301 PointerProperties buildProperties() const { return mProperties; }
1302
1303 PointerCoords buildCoords() const { return mCoords; }
1304
1305private:
1306 PointerProperties mProperties;
1307 PointerCoords mCoords;
1308};
1309
1310class MotionEventBuilder {
1311public:
1312 MotionEventBuilder(int32_t action, int32_t source) {
1313 mAction = action;
1314 mSource = source;
1315 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1316 }
1317
1318 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1319 mEventTime = eventTime;
1320 return *this;
1321 }
1322
1323 MotionEventBuilder& displayId(int32_t displayId) {
1324 mDisplayId = displayId;
1325 return *this;
1326 }
1327
1328 MotionEventBuilder& actionButton(int32_t actionButton) {
1329 mActionButton = actionButton;
1330 return *this;
1331 }
1332
arthurhung6d4bed92021-03-17 11:59:33 +08001333 MotionEventBuilder& buttonState(int32_t buttonState) {
1334 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001335 return *this;
1336 }
1337
1338 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1339 mRawXCursorPosition = rawXCursorPosition;
1340 return *this;
1341 }
1342
1343 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1344 mRawYCursorPosition = rawYCursorPosition;
1345 return *this;
1346 }
1347
1348 MotionEventBuilder& pointer(PointerBuilder pointer) {
1349 mPointers.push_back(pointer);
1350 return *this;
1351 }
1352
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001353 MotionEventBuilder& addFlag(uint32_t flags) {
1354 mFlags |= flags;
1355 return *this;
1356 }
1357
Garfield Tandf26e862020-07-01 20:18:19 -07001358 MotionEvent build() {
1359 std::vector<PointerProperties> pointerProperties;
1360 std::vector<PointerCoords> pointerCoords;
1361 for (const PointerBuilder& pointer : mPointers) {
1362 pointerProperties.push_back(pointer.buildProperties());
1363 pointerCoords.push_back(pointer.buildCoords());
1364 }
1365
1366 // Set mouse cursor position for the most common cases to avoid boilerplate.
1367 if (mSource == AINPUT_SOURCE_MOUSE &&
1368 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1369 mPointers.size() == 1) {
1370 mRawXCursorPosition = pointerCoords[0].getX();
1371 mRawYCursorPosition = pointerCoords[0].getY();
1372 }
1373
1374 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001375 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001376 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001377 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001378 mButtonState, MotionClassification::NONE, identityTransform,
1379 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001380 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1381 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001382
1383 return event;
1384 }
1385
1386private:
1387 int32_t mAction;
1388 int32_t mSource;
1389 nsecs_t mEventTime;
1390 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1391 int32_t mActionButton{0};
1392 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001393 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001394 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1395 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1396
1397 std::vector<PointerBuilder> mPointers;
1398};
1399
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001400static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001401 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001402 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001403 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001404 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1405 injectionTimeout,
1406 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1407}
1408
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001409static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001410 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001411 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001412 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001413 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1414 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001415 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001416 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001417 MotionEvent event = MotionEventBuilder(action, source)
1418 .displayId(displayId)
1419 .eventTime(eventTime)
1420 .rawXCursorPosition(cursorPosition.x)
1421 .rawYCursorPosition(cursorPosition.y)
1422 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1423 .x(position.x)
1424 .y(position.y))
1425 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001426
1427 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001428 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001429}
1430
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001431static InputEventInjectionResult injectMotionDown(
1432 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1433 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001434 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001435}
1436
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001437static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001438 int32_t source, int32_t displayId,
1439 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001440 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001441}
1442
Jackal Guof9696682018-10-05 12:23:23 +08001443static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1444 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1445 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001446 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1447 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1448 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001449
1450 return args;
1451}
1452
chaviwd1c23182019-12-20 18:44:56 -08001453static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1454 const std::vector<PointF>& points) {
1455 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001456 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1457 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1458 }
1459
chaviwd1c23182019-12-20 18:44:56 -08001460 PointerProperties pointerProperties[pointerCount];
1461 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001462
chaviwd1c23182019-12-20 18:44:56 -08001463 for (size_t i = 0; i < pointerCount; i++) {
1464 pointerProperties[i].clear();
1465 pointerProperties[i].id = i;
1466 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001467
chaviwd1c23182019-12-20 18:44:56 -08001468 pointerCoords[i].clear();
1469 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1470 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1471 }
Jackal Guof9696682018-10-05 12:23:23 +08001472
1473 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1474 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001475 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001476 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1477 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001478 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1479 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001480 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1481 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001482
1483 return args;
1484}
1485
chaviwd1c23182019-12-20 18:44:56 -08001486static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1487 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1488}
1489
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001490static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1491 const PointerCaptureRequest& request) {
1492 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001493}
1494
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001495/**
1496 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1497 * broken channel.
1498 */
1499TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1500 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1501 sp<FakeWindowHandle> window =
1502 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1503 ADISPLAY_ID_DEFAULT);
1504
1505 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1506
1507 // Window closes its channel, but the window remains.
1508 window->destroyReceiver();
1509 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1510}
1511
Arthur Hungb92218b2018-08-14 12:00:21 +08001512TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001513 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001514 sp<FakeWindowHandle> window =
1515 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001516
Arthur Hung72d8dc32020-03-28 00:48:39 +00001517 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001518 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1519 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1520 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001521
1522 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001523 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001524}
1525
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001526TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1527 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1528 sp<FakeWindowHandle> window =
1529 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1530
1531 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1532 // Inject a MotionEvent to an unknown display.
1533 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1534 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1535 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1536
1537 // Window should receive motion event.
1538 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1539}
1540
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001541/**
1542 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1543 * To ensure that window receives only events that were directly inside of it, add
1544 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1545 * when finding touched windows.
1546 * This test serves as a sanity check for the next test, where setInputWindows is
1547 * called twice.
1548 */
1549TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001550 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001551 sp<FakeWindowHandle> window =
1552 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1553 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001554 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001555
1556 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001557 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001558 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1559 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001560 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001561
1562 // Window should receive motion event.
1563 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1564}
1565
1566/**
1567 * Calling setInputWindows twice, with the same info, should not cause any issues.
1568 * To ensure that window receives only events that were directly inside of it, add
1569 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1570 * when finding touched windows.
1571 */
1572TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001573 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001574 sp<FakeWindowHandle> window =
1575 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1576 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001577 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001578
1579 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1580 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001581 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001582 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1583 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001584 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001585
1586 // Window should receive motion event.
1587 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1588}
1589
Arthur Hungb92218b2018-08-14 12:00:21 +08001590// The foreground window should receive the first touch down event.
1591TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001592 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001593 sp<FakeWindowHandle> windowTop =
1594 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1595 sp<FakeWindowHandle> windowSecond =
1596 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001597
Arthur Hung72d8dc32020-03-28 00:48:39 +00001598 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001599 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1600 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1601 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001602
1603 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001604 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001605 windowSecond->assertNoEvents();
1606}
1607
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001608/**
1609 * Two windows: A top window, and a wallpaper behind the window.
1610 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1611 * gets ACTION_CANCEL.
1612 * 1. foregroundWindow <-- has wallpaper (hasWallpaper=true)
1613 * 2. wallpaperWindow <-- is wallpaper (type=InputWindowInfo::Type::WALLPAPER)
1614 */
1615TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1616 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1617 sp<FakeWindowHandle> foregroundWindow =
1618 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1619 foregroundWindow->setHasWallpaper(true);
1620 sp<FakeWindowHandle> wallpaperWindow =
1621 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1622 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1623 constexpr int expectedWallpaperFlags =
1624 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1625
1626 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1627 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1628 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1629 {100, 200}))
1630 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1631
1632 // Both foreground window and its wallpaper should receive the touch down
1633 foregroundWindow->consumeMotionDown();
1634 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1635
1636 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1637 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1638 ADISPLAY_ID_DEFAULT, {110, 200}))
1639 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1640
1641 foregroundWindow->consumeMotionMove();
1642 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1643
1644 // Now the foreground window goes away, but the wallpaper stays
1645 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1646 foregroundWindow->consumeMotionCancel();
1647 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1648 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1649}
1650
1651/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001652 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1653 * with the following differences:
1654 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1655 * clean up the connection.
1656 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1657 * Ensure that there's no crash in the dispatcher.
1658 */
1659TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1660 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1661 sp<FakeWindowHandle> foregroundWindow =
1662 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1663 foregroundWindow->setHasWallpaper(true);
1664 sp<FakeWindowHandle> wallpaperWindow =
1665 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1666 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1667 constexpr int expectedWallpaperFlags =
1668 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1669
1670 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1671 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1672 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1673 {100, 200}))
1674 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1675
1676 // Both foreground window and its wallpaper should receive the touch down
1677 foregroundWindow->consumeMotionDown();
1678 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1679
1680 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1681 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1682 ADISPLAY_ID_DEFAULT, {110, 200}))
1683 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1684
1685 foregroundWindow->consumeMotionMove();
1686 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1687
1688 // Wallpaper closes its channel, but the window remains.
1689 wallpaperWindow->destroyReceiver();
1690 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1691
1692 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1693 // is no longer valid.
1694 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1695 foregroundWindow->consumeMotionCancel();
1696}
1697
1698/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001699 * A single window that receives touch (on top), and a wallpaper window underneath it.
1700 * The top window gets a multitouch gesture.
1701 * Ensure that wallpaper gets the same gesture.
1702 */
1703TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1704 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1705 sp<FakeWindowHandle> window =
1706 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1707 window->setHasWallpaper(true);
1708
1709 sp<FakeWindowHandle> wallpaperWindow =
1710 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1711 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1712 constexpr int expectedWallpaperFlags =
1713 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1714
1715 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1716
1717 // Touch down on top window
1718 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1719 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1720 {100, 100}))
1721 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1722
1723 // Both top window and its wallpaper should receive the touch down
1724 window->consumeMotionDown();
1725 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1726
1727 // Second finger down on the top window
1728 const MotionEvent secondFingerDownEvent =
1729 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1730 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1731 AINPUT_SOURCE_TOUCHSCREEN)
1732 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1733 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1734 .x(100)
1735 .y(100))
1736 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1737 .x(150)
1738 .y(150))
1739 .build();
1740 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1741 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1742 InputEventInjectionSync::WAIT_FOR_RESULT))
1743 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1744
1745 window->consumeMotionPointerDown(1 /* pointerIndex */);
1746 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1747 expectedWallpaperFlags);
1748 window->assertNoEvents();
1749 wallpaperWindow->assertNoEvents();
1750}
1751
1752/**
1753 * Two windows: a window on the left and window on the right.
1754 * A third window, wallpaper, is behind both windows, and spans both top windows.
1755 * The first touch down goes to the left window. A second pointer touches down on the right window.
1756 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1757 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1758 * ACTION_POINTER_DOWN(1).
1759 */
1760TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1761 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1762 sp<FakeWindowHandle> leftWindow =
1763 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1764 leftWindow->setFrame(Rect(0, 0, 200, 200));
1765 leftWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1766 leftWindow->setHasWallpaper(true);
1767
1768 sp<FakeWindowHandle> rightWindow =
1769 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1770 rightWindow->setFrame(Rect(200, 0, 400, 200));
1771 rightWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1772 rightWindow->setHasWallpaper(true);
1773
1774 sp<FakeWindowHandle> wallpaperWindow =
1775 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1776 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
1777 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1778 constexpr int expectedWallpaperFlags =
1779 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1780
1781 mDispatcher->setInputWindows(
1782 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1783
1784 // Touch down on left window
1785 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1786 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1787 {100, 100}))
1788 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1789
1790 // Both foreground window and its wallpaper should receive the touch down
1791 leftWindow->consumeMotionDown();
1792 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1793
1794 // Second finger down on the right window
1795 const MotionEvent secondFingerDownEvent =
1796 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1797 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1798 AINPUT_SOURCE_TOUCHSCREEN)
1799 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1800 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1801 .x(100)
1802 .y(100))
1803 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1804 .x(300)
1805 .y(100))
1806 .build();
1807 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1808 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1809 InputEventInjectionSync::WAIT_FOR_RESULT))
1810 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1811
1812 leftWindow->consumeMotionMove();
1813 // Since the touch is split, right window gets ACTION_DOWN
1814 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1815 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1816 expectedWallpaperFlags);
1817
1818 // Now, leftWindow, which received the first finger, disappears.
1819 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1820 leftWindow->consumeMotionCancel();
1821 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1822 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1823
1824 // The pointer that's still down on the right window moves, and goes to the right window only.
1825 // As far as the dispatcher's concerned though, both pointers are still present.
1826 const MotionEvent secondFingerMoveEvent =
1827 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1828 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1829 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1830 .x(100)
1831 .y(100))
1832 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1833 .x(310)
1834 .y(110))
1835 .build();
1836 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1837 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1838 InputEventInjectionSync::WAIT_FOR_RESULT));
1839 rightWindow->consumeMotionMove();
1840
1841 leftWindow->assertNoEvents();
1842 rightWindow->assertNoEvents();
1843 wallpaperWindow->assertNoEvents();
1844}
1845
Garfield Tandf26e862020-07-01 20:18:19 -07001846TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001847 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001848 sp<FakeWindowHandle> windowLeft =
1849 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1850 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001851 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001852 sp<FakeWindowHandle> windowRight =
1853 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1854 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001855 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001856
1857 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1858
1859 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1860
1861 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001862 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001863 injectMotionEvent(mDispatcher,
1864 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1865 AINPUT_SOURCE_MOUSE)
1866 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1867 .x(900)
1868 .y(400))
1869 .build()));
1870 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1871 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1872 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1873 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1874
1875 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001876 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001877 injectMotionEvent(mDispatcher,
1878 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1879 AINPUT_SOURCE_MOUSE)
1880 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1881 .x(300)
1882 .y(400))
1883 .build()));
1884 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1885 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1886 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1887 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1888 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1889 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1890
1891 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001892 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001893 injectMotionEvent(mDispatcher,
1894 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1895 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1896 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1897 .x(300)
1898 .y(400))
1899 .build()));
1900 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1901
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001902 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001903 injectMotionEvent(mDispatcher,
1904 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1905 AINPUT_SOURCE_MOUSE)
1906 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1907 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1908 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1909 .x(300)
1910 .y(400))
1911 .build()));
1912 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1913 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1914
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001915 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001916 injectMotionEvent(mDispatcher,
1917 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1918 AINPUT_SOURCE_MOUSE)
1919 .buttonState(0)
1920 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1921 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1922 .x(300)
1923 .y(400))
1924 .build()));
1925 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1926 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1927
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001928 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001929 injectMotionEvent(mDispatcher,
1930 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1931 .buttonState(0)
1932 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1933 .x(300)
1934 .y(400))
1935 .build()));
1936 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1937
1938 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001939 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001940 injectMotionEvent(mDispatcher,
1941 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1942 AINPUT_SOURCE_MOUSE)
1943 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1944 .x(900)
1945 .y(400))
1946 .build()));
1947 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1948 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1949 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1950 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1951 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1952 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1953}
1954
1955// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1956// directly in this test.
1957TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001958 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001959 sp<FakeWindowHandle> window =
1960 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1961 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001962 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001963
1964 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1965
1966 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1967
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001968 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001969 injectMotionEvent(mDispatcher,
1970 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1971 AINPUT_SOURCE_MOUSE)
1972 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1973 .x(300)
1974 .y(400))
1975 .build()));
1976 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1977 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1978
1979 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001980 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001981 injectMotionEvent(mDispatcher,
1982 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1983 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1984 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1985 .x(300)
1986 .y(400))
1987 .build()));
1988 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1989
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001990 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001991 injectMotionEvent(mDispatcher,
1992 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1993 AINPUT_SOURCE_MOUSE)
1994 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1995 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1996 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1997 .x(300)
1998 .y(400))
1999 .build()));
2000 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2001 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2002
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002003 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002004 injectMotionEvent(mDispatcher,
2005 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2006 AINPUT_SOURCE_MOUSE)
2007 .buttonState(0)
2008 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2009 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2010 .x(300)
2011 .y(400))
2012 .build()));
2013 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2014 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2015
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002016 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002017 injectMotionEvent(mDispatcher,
2018 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2019 .buttonState(0)
2020 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2021 .x(300)
2022 .y(400))
2023 .build()));
2024 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2025
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002026 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002027 injectMotionEvent(mDispatcher,
2028 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2029 AINPUT_SOURCE_MOUSE)
2030 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2031 .x(300)
2032 .y(400))
2033 .build()));
2034 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2035 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2036}
2037
Garfield Tan00f511d2019-06-12 16:55:40 -07002038TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002039 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002040
2041 sp<FakeWindowHandle> windowLeft =
2042 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2043 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002044 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002045 sp<FakeWindowHandle> windowRight =
2046 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2047 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05002048 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002049
2050 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2051
Arthur Hung72d8dc32020-03-28 00:48:39 +00002052 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002053
2054 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2055 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002056 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002057 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002058 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002059 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002060 windowRight->assertNoEvents();
2061}
2062
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002063TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002064 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002065 sp<FakeWindowHandle> window =
2066 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002067 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002068
Arthur Hung72d8dc32020-03-28 00:48:39 +00002069 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002070 setFocusedWindow(window);
2071
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002072 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002073
2074 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2075 mDispatcher->notifyKey(&keyArgs);
2076
2077 // Window should receive key down event.
2078 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2079
2080 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2081 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002082 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002083 mDispatcher->notifyDeviceReset(&args);
2084 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2085 AKEY_EVENT_FLAG_CANCELED);
2086}
2087
2088TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002089 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002090 sp<FakeWindowHandle> window =
2091 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2092
Arthur Hung72d8dc32020-03-28 00:48:39 +00002093 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002094
2095 NotifyMotionArgs motionArgs =
2096 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2097 ADISPLAY_ID_DEFAULT);
2098 mDispatcher->notifyMotion(&motionArgs);
2099
2100 // Window should receive motion down event.
2101 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2102
2103 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2104 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002105 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002106 mDispatcher->notifyDeviceReset(&args);
2107 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2108 0 /*expectedFlags*/);
2109}
2110
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002111/**
2112 * Ensure the correct coordinate spaces are used by InputDispatcher.
2113 *
2114 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2115 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2116 * space.
2117 */
2118class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2119public:
2120 void SetUp() override {
2121 InputDispatcherTest::SetUp();
2122 mDisplayInfos.clear();
2123 mWindowInfos.clear();
2124 }
2125
2126 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2127 gui::DisplayInfo info;
2128 info.displayId = displayId;
2129 info.transform = transform;
2130 mDisplayInfos.push_back(std::move(info));
2131 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2132 }
2133
2134 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2135 mWindowInfos.push_back(*windowHandle->getInfo());
2136 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2137 }
2138
2139 // Set up a test scenario where the display has a scaled projection and there are two windows
2140 // on the display.
2141 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2142 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2143 // respectively.
2144 ui::Transform displayTransform;
2145 displayTransform.set(2, 0, 0, 4);
2146 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2147
2148 std::shared_ptr<FakeApplicationHandle> application =
2149 std::make_shared<FakeApplicationHandle>();
2150
2151 // Add two windows to the display. Their frames are represented in the display space.
2152 sp<FakeWindowHandle> firstWindow =
2153 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2154 firstWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2155 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2156 addWindow(firstWindow);
2157
2158 sp<FakeWindowHandle> secondWindow =
2159 new FakeWindowHandle(application, mDispatcher, "Second Window",
2160 ADISPLAY_ID_DEFAULT);
2161 secondWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2162 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2163 addWindow(secondWindow);
2164 return {std::move(firstWindow), std::move(secondWindow)};
2165 }
2166
2167private:
2168 std::vector<gui::DisplayInfo> mDisplayInfos;
2169 std::vector<gui::WindowInfo> mWindowInfos;
2170};
2171
2172TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2173 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2174 // Send down to the first window. The point is represented in the display space. The point is
2175 // selected so that if the hit test was done with the transform applied to it, then it would
2176 // end up in the incorrect window.
2177 NotifyMotionArgs downMotionArgs =
2178 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2179 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2180 mDispatcher->notifyMotion(&downMotionArgs);
2181
2182 firstWindow->consumeMotionDown();
2183 secondWindow->assertNoEvents();
2184}
2185
2186// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2187// the event should be treated as being in the logical display space.
2188TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2189 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2190 // Send down to the first window. The point is represented in the logical display space. The
2191 // point is selected so that if the hit test was done in logical display space, then it would
2192 // end up in the incorrect window.
2193 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2194 PointF{75 * 2, 55 * 4});
2195
2196 firstWindow->consumeMotionDown();
2197 secondWindow->assertNoEvents();
2198}
2199
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002200// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2201// event should be treated as being in the logical display space.
2202TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2203 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2204
2205 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2206 ui::Transform injectedEventTransform;
2207 injectedEventTransform.set(matrix);
2208 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2209 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2210
2211 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2212 .displayId(ADISPLAY_ID_DEFAULT)
2213 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2214 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2215 .x(untransformedPoint.x)
2216 .y(untransformedPoint.y))
2217 .build();
2218 event.transform(matrix);
2219
2220 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2221 InputEventInjectionSync::WAIT_FOR_RESULT);
2222
2223 firstWindow->consumeMotionDown();
2224 secondWindow->assertNoEvents();
2225}
2226
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002227TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2228 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2229
2230 // Send down to the second window.
2231 NotifyMotionArgs downMotionArgs =
2232 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2233 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2234 mDispatcher->notifyMotion(&downMotionArgs);
2235
2236 firstWindow->assertNoEvents();
2237 const MotionEvent* event = secondWindow->consumeMotion();
2238 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2239
2240 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2241 EXPECT_EQ(300, event->getRawX(0));
2242 EXPECT_EQ(880, event->getRawY(0));
2243
2244 // Ensure that the x and y values are in the window's coordinate space.
2245 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2246 // the logical display space. This will be the origin of the window space.
2247 EXPECT_EQ(100, event->getX(0));
2248 EXPECT_EQ(80, event->getY(0));
2249}
2250
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002251using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2252 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002253
2254class TransferTouchFixture : public InputDispatcherTest,
2255 public ::testing::WithParamInterface<TransferFunction> {};
2256
2257TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002258 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002259
2260 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002261 sp<FakeWindowHandle> firstWindow =
2262 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2263 sp<FakeWindowHandle> secondWindow =
2264 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002265
2266 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002267 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002268
2269 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002270 NotifyMotionArgs downMotionArgs =
2271 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2272 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002273 mDispatcher->notifyMotion(&downMotionArgs);
2274 // Only the first window should get the down event
2275 firstWindow->consumeMotionDown();
2276 secondWindow->assertNoEvents();
2277
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002278 // Transfer touch to the second window
2279 TransferFunction f = GetParam();
2280 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2281 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002282 // The first window gets cancel and the second gets down
2283 firstWindow->consumeMotionCancel();
2284 secondWindow->consumeMotionDown();
2285
2286 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002287 NotifyMotionArgs upMotionArgs =
2288 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2289 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002290 mDispatcher->notifyMotion(&upMotionArgs);
2291 // The first window gets no events and the second gets up
2292 firstWindow->assertNoEvents();
2293 secondWindow->consumeMotionUp();
2294}
2295
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002296TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002297 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002298
2299 PointF touchPoint = {10, 10};
2300
2301 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002302 sp<FakeWindowHandle> firstWindow =
2303 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2304 sp<FakeWindowHandle> secondWindow =
2305 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002306
2307 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002308 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002309
2310 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002311 NotifyMotionArgs downMotionArgs =
2312 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2313 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002314 mDispatcher->notifyMotion(&downMotionArgs);
2315 // Only the first window should get the down event
2316 firstWindow->consumeMotionDown();
2317 secondWindow->assertNoEvents();
2318
2319 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002320 NotifyMotionArgs pointerDownMotionArgs =
2321 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2322 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2323 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2324 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002325 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2326 // Only the first window should get the pointer down event
2327 firstWindow->consumeMotionPointerDown(1);
2328 secondWindow->assertNoEvents();
2329
2330 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002331 TransferFunction f = GetParam();
2332 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2333 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002334 // The first window gets cancel and the second gets down and pointer down
2335 firstWindow->consumeMotionCancel();
2336 secondWindow->consumeMotionDown();
2337 secondWindow->consumeMotionPointerDown(1);
2338
2339 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002340 NotifyMotionArgs pointerUpMotionArgs =
2341 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2342 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2343 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2344 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002345 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2346 // The first window gets nothing and the second gets pointer up
2347 firstWindow->assertNoEvents();
2348 secondWindow->consumeMotionPointerUp(1);
2349
2350 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002351 NotifyMotionArgs upMotionArgs =
2352 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2353 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002354 mDispatcher->notifyMotion(&upMotionArgs);
2355 // The first window gets nothing and the second gets up
2356 firstWindow->assertNoEvents();
2357 secondWindow->consumeMotionUp();
2358}
2359
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002360// For the cases of single pointer touch and two pointers non-split touch, the api's
2361// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2362// for the case where there are multiple pointers split across several windows.
2363INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2364 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002365 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2366 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002367 return dispatcher->transferTouch(destChannelToken);
2368 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002369 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2370 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002371 return dispatcher->transferTouchFocus(from, to,
2372 false /*isDragAndDrop*/);
2373 }));
2374
Svet Ganov5d3bc372020-01-26 23:11:07 -08002375TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002376 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002377
2378 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002379 sp<FakeWindowHandle> firstWindow =
2380 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002381 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002382 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002383
2384 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002385 sp<FakeWindowHandle> secondWindow =
2386 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002387 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002388 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002389
2390 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002391 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002392
2393 PointF pointInFirst = {300, 200};
2394 PointF pointInSecond = {300, 600};
2395
2396 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002397 NotifyMotionArgs firstDownMotionArgs =
2398 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2399 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002400 mDispatcher->notifyMotion(&firstDownMotionArgs);
2401 // Only the first window should get the down event
2402 firstWindow->consumeMotionDown();
2403 secondWindow->assertNoEvents();
2404
2405 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002406 NotifyMotionArgs secondDownMotionArgs =
2407 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2408 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2409 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2410 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002411 mDispatcher->notifyMotion(&secondDownMotionArgs);
2412 // The first window gets a move and the second a down
2413 firstWindow->consumeMotionMove();
2414 secondWindow->consumeMotionDown();
2415
2416 // Transfer touch focus to the second window
2417 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2418 // The first window gets cancel and the new gets pointer down (it already saw down)
2419 firstWindow->consumeMotionCancel();
2420 secondWindow->consumeMotionPointerDown(1);
2421
2422 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002423 NotifyMotionArgs pointerUpMotionArgs =
2424 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2425 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2426 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2427 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002428 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2429 // The first window gets nothing and the second gets pointer up
2430 firstWindow->assertNoEvents();
2431 secondWindow->consumeMotionPointerUp(1);
2432
2433 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002434 NotifyMotionArgs upMotionArgs =
2435 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2436 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002437 mDispatcher->notifyMotion(&upMotionArgs);
2438 // The first window gets nothing and the second gets up
2439 firstWindow->assertNoEvents();
2440 secondWindow->consumeMotionUp();
2441}
2442
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002443// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2444// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2445// touch is not supported, so the touch should continue on those windows and the transferred-to
2446// window should get nothing.
2447TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2448 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2449
2450 // Create a non touch modal window that supports split touch
2451 sp<FakeWindowHandle> firstWindow =
2452 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2453 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002454 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002455
2456 // Create a non touch modal window that supports split touch
2457 sp<FakeWindowHandle> secondWindow =
2458 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2459 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002460 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002461
2462 // Add the windows to the dispatcher
2463 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2464
2465 PointF pointInFirst = {300, 200};
2466 PointF pointInSecond = {300, 600};
2467
2468 // Send down to the first window
2469 NotifyMotionArgs firstDownMotionArgs =
2470 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2471 ADISPLAY_ID_DEFAULT, {pointInFirst});
2472 mDispatcher->notifyMotion(&firstDownMotionArgs);
2473 // Only the first window should get the down event
2474 firstWindow->consumeMotionDown();
2475 secondWindow->assertNoEvents();
2476
2477 // Send down to the second window
2478 NotifyMotionArgs secondDownMotionArgs =
2479 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2480 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2481 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2482 {pointInFirst, pointInSecond});
2483 mDispatcher->notifyMotion(&secondDownMotionArgs);
2484 // The first window gets a move and the second a down
2485 firstWindow->consumeMotionMove();
2486 secondWindow->consumeMotionDown();
2487
2488 // Transfer touch focus to the second window
2489 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2490 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2491 ASSERT_FALSE(transferred);
2492 firstWindow->assertNoEvents();
2493 secondWindow->assertNoEvents();
2494
2495 // The rest of the dispatch should proceed as normal
2496 // Send pointer up to the second window
2497 NotifyMotionArgs pointerUpMotionArgs =
2498 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2499 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2500 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2501 {pointInFirst, pointInSecond});
2502 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2503 // The first window gets MOVE and the second gets pointer up
2504 firstWindow->consumeMotionMove();
2505 secondWindow->consumeMotionUp();
2506
2507 // Send up event to the first window
2508 NotifyMotionArgs upMotionArgs =
2509 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2510 ADISPLAY_ID_DEFAULT);
2511 mDispatcher->notifyMotion(&upMotionArgs);
2512 // The first window gets nothing and the second gets up
2513 firstWindow->consumeMotionUp();
2514 secondWindow->assertNoEvents();
2515}
2516
Arthur Hungabbb9d82021-09-01 14:52:30 +00002517// This case will create two windows and one mirrored window on the default display and mirror
2518// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2519// the windows info of second display before default display.
2520TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2521 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2522 sp<FakeWindowHandle> firstWindowInPrimary =
2523 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2524 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2525 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2526 sp<FakeWindowHandle> secondWindowInPrimary =
2527 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2528 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2529 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2530
2531 sp<FakeWindowHandle> mirrorWindowInPrimary =
2532 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2533 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2534 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2535
2536 sp<FakeWindowHandle> firstWindowInSecondary =
2537 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2538 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2539 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2540
2541 sp<FakeWindowHandle> secondWindowInSecondary =
2542 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2543 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2544 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2545
2546 // Update window info, let it find window handle of second display first.
2547 mDispatcher->setInputWindows(
2548 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2549 {ADISPLAY_ID_DEFAULT,
2550 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2551
2552 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2553 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2554 {50, 50}))
2555 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2556
2557 // Window should receive motion event.
2558 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2559
2560 // Transfer touch focus
2561 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2562 secondWindowInPrimary->getToken()));
2563 // The first window gets cancel.
2564 firstWindowInPrimary->consumeMotionCancel();
2565 secondWindowInPrimary->consumeMotionDown();
2566
2567 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2568 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2569 ADISPLAY_ID_DEFAULT, {150, 50}))
2570 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2571 firstWindowInPrimary->assertNoEvents();
2572 secondWindowInPrimary->consumeMotionMove();
2573
2574 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2575 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2576 {150, 50}))
2577 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2578 firstWindowInPrimary->assertNoEvents();
2579 secondWindowInPrimary->consumeMotionUp();
2580}
2581
2582// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2583// 'transferTouch' api.
2584TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2585 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2586 sp<FakeWindowHandle> firstWindowInPrimary =
2587 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2588 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2589 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2590 sp<FakeWindowHandle> secondWindowInPrimary =
2591 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2592 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2593 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2594
2595 sp<FakeWindowHandle> mirrorWindowInPrimary =
2596 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2597 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2598 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2599
2600 sp<FakeWindowHandle> firstWindowInSecondary =
2601 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2602 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2603 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2604
2605 sp<FakeWindowHandle> secondWindowInSecondary =
2606 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2607 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2608 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2609
2610 // Update window info, let it find window handle of second display first.
2611 mDispatcher->setInputWindows(
2612 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2613 {ADISPLAY_ID_DEFAULT,
2614 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2615
2616 // Touch on second display.
2617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2618 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2619 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2620
2621 // Window should receive motion event.
2622 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2623
2624 // Transfer touch focus
2625 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2626
2627 // The first window gets cancel.
2628 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2629 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2630
2631 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2632 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2633 SECOND_DISPLAY_ID, {150, 50}))
2634 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2635 firstWindowInPrimary->assertNoEvents();
2636 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2637
2638 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2639 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2640 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2641 firstWindowInPrimary->assertNoEvents();
2642 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2643}
2644
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002645TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002646 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002647 sp<FakeWindowHandle> window =
2648 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2649
Vishnu Nair47074b82020-08-14 11:54:47 -07002650 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002651 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002652 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002653
2654 window->consumeFocusEvent(true);
2655
2656 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2657 mDispatcher->notifyKey(&keyArgs);
2658
2659 // Window should receive key down event.
2660 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2661}
2662
2663TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002664 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002665 sp<FakeWindowHandle> window =
2666 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2667
Arthur Hung72d8dc32020-03-28 00:48:39 +00002668 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002669
2670 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2671 mDispatcher->notifyKey(&keyArgs);
2672 mDispatcher->waitForIdle();
2673
2674 window->assertNoEvents();
2675}
2676
2677// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2678TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002679 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002680 sp<FakeWindowHandle> window =
2681 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2682
Arthur Hung72d8dc32020-03-28 00:48:39 +00002683 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002684
2685 // Send key
2686 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2687 mDispatcher->notifyKey(&keyArgs);
2688 // Send motion
2689 NotifyMotionArgs motionArgs =
2690 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2691 ADISPLAY_ID_DEFAULT);
2692 mDispatcher->notifyMotion(&motionArgs);
2693
2694 // Window should receive only the motion event
2695 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2696 window->assertNoEvents(); // Key event or focus event will not be received
2697}
2698
arthurhungea3f4fc2020-12-21 23:18:53 +08002699TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2700 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2701
2702 // Create first non touch modal window that supports split touch
2703 sp<FakeWindowHandle> firstWindow =
2704 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2705 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002706 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002707
2708 // Create second non touch modal window that supports split touch
2709 sp<FakeWindowHandle> secondWindow =
2710 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2711 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002712 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002713
2714 // Add the windows to the dispatcher
2715 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2716
2717 PointF pointInFirst = {300, 200};
2718 PointF pointInSecond = {300, 600};
2719
2720 // Send down to the first window
2721 NotifyMotionArgs firstDownMotionArgs =
2722 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2723 ADISPLAY_ID_DEFAULT, {pointInFirst});
2724 mDispatcher->notifyMotion(&firstDownMotionArgs);
2725 // Only the first window should get the down event
2726 firstWindow->consumeMotionDown();
2727 secondWindow->assertNoEvents();
2728
2729 // Send down to the second window
2730 NotifyMotionArgs secondDownMotionArgs =
2731 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2732 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2733 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2734 {pointInFirst, pointInSecond});
2735 mDispatcher->notifyMotion(&secondDownMotionArgs);
2736 // The first window gets a move and the second a down
2737 firstWindow->consumeMotionMove();
2738 secondWindow->consumeMotionDown();
2739
2740 // Send pointer cancel to the second window
2741 NotifyMotionArgs pointerUpMotionArgs =
2742 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2743 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2744 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2745 {pointInFirst, pointInSecond});
2746 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2747 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2748 // The first window gets move and the second gets cancel.
2749 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2750 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2751
2752 // Send up event.
2753 NotifyMotionArgs upMotionArgs =
2754 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2755 ADISPLAY_ID_DEFAULT);
2756 mDispatcher->notifyMotion(&upMotionArgs);
2757 // The first window gets up and the second gets nothing.
2758 firstWindow->consumeMotionUp();
2759 secondWindow->assertNoEvents();
2760}
2761
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002762TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2763 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2764
2765 sp<FakeWindowHandle> window =
2766 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2767 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2768 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2769 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2770 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2771
2772 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2773 window->assertNoEvents();
2774 mDispatcher->waitForIdle();
2775}
2776
chaviwd1c23182019-12-20 18:44:56 -08002777class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002778public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002779 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002780 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07002781 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002782 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002783 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002784 }
2785
chaviwd1c23182019-12-20 18:44:56 -08002786 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2787
2788 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2789 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2790 expectedDisplayId, expectedFlags);
2791 }
2792
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002793 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2794
2795 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2796
chaviwd1c23182019-12-20 18:44:56 -08002797 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2798 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2799 expectedDisplayId, expectedFlags);
2800 }
2801
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002802 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2803 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2804 expectedDisplayId, expectedFlags);
2805 }
2806
chaviwd1c23182019-12-20 18:44:56 -08002807 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2808 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2809 expectedDisplayId, expectedFlags);
2810 }
2811
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002812 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2813 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2814 expectedDisplayId, expectedFlags);
2815 }
2816
Arthur Hungfbfa5722021-11-16 02:45:54 +00002817 void consumeMotionPointerDown(int32_t pointerIdx) {
2818 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2819 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2820 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2821 0 /*expectedFlags*/);
2822 }
2823
Evan Rosky84f07f02021-04-16 10:42:42 -07002824 MotionEvent* consumeMotion() {
2825 InputEvent* event = mInputReceiver->consume();
2826 if (!event) {
2827 ADD_FAILURE() << "No event was produced";
2828 return nullptr;
2829 }
2830 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2831 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2832 return nullptr;
2833 }
2834 return static_cast<MotionEvent*>(event);
2835 }
2836
chaviwd1c23182019-12-20 18:44:56 -08002837 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2838
2839private:
2840 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002841};
2842
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002843using InputDispatcherMonitorTest = InputDispatcherTest;
2844
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002845/**
2846 * Two entities that receive touch: A window, and a global monitor.
2847 * The touch goes to the window, and then the window disappears.
2848 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2849 * for the monitor, as well.
2850 * 1. foregroundWindow
2851 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2852 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002853TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002854 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2855 sp<FakeWindowHandle> window =
2856 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2857
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002858 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002859
2860 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2861 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2862 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2863 {100, 200}))
2864 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2865
2866 // Both the foreground window and the global monitor should receive the touch down
2867 window->consumeMotionDown();
2868 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2869
2870 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2871 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2872 ADISPLAY_ID_DEFAULT, {110, 200}))
2873 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2874
2875 window->consumeMotionMove();
2876 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2877
2878 // Now the foreground window goes away
2879 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2880 window->consumeMotionCancel();
2881 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2882
2883 // If more events come in, there will be no more foreground window to send them to. This will
2884 // cause a cancel for the monitor, as well.
2885 ASSERT_EQ(InputEventInjectionResult::FAILED,
2886 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2887 ADISPLAY_ID_DEFAULT, {120, 200}))
2888 << "Injection should fail because the window was removed";
2889 window->assertNoEvents();
2890 // Global monitor now gets the cancel
2891 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2892}
2893
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002894TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002895 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002896 sp<FakeWindowHandle> window =
2897 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002898 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002899
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002900 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002901
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002902 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002903 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002904 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002905 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002906 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002907}
2908
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002909TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
2910 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002911
Chris Yea209fde2020-07-22 13:54:51 -07002912 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002913 sp<FakeWindowHandle> window =
2914 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002915 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002916
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002917 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002918 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002919 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002920 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002921 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002922
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002923 // Pilfer pointers from the monitor.
2924 // This should not do anything and the window should continue to receive events.
2925 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00002926
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002927 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002928 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2929 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002930 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002931
2932 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2933 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002934}
2935
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002936TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07002937 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2938 sp<FakeWindowHandle> window =
2939 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2940 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2941 window->setWindowOffset(20, 40);
2942 window->setWindowTransform(0, 1, -1, 0);
2943
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002944 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07002945
2946 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2947 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2948 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2949 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2950 MotionEvent* event = monitor.consumeMotion();
2951 // Even though window has transform, gesture monitor must not.
2952 ASSERT_EQ(ui::Transform(), event->getTransform());
2953}
2954
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002955TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002956 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002957 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00002958
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002959 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00002960 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002961 << "Injection should fail if there is a monitor, but no touchable window";
2962 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00002963}
2964
chaviw81e2bb92019-12-18 15:03:51 -08002965TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002966 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002967 sp<FakeWindowHandle> window =
2968 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2969
Arthur Hung72d8dc32020-03-28 00:48:39 +00002970 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002971
2972 NotifyMotionArgs motionArgs =
2973 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2974 ADISPLAY_ID_DEFAULT);
2975
2976 mDispatcher->notifyMotion(&motionArgs);
2977 // Window should receive motion down event.
2978 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2979
2980 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002981 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002982 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2983 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2984 motionArgs.pointerCoords[0].getX() - 10);
2985
2986 mDispatcher->notifyMotion(&motionArgs);
2987 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2988 0 /*expectedFlags*/);
2989}
2990
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002991/**
2992 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2993 * the device default right away. In the test scenario, we check both the default value,
2994 * and the action of enabling / disabling.
2995 */
2996TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002997 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002998 sp<FakeWindowHandle> window =
2999 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003000 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003001
3002 // Set focused application.
3003 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003004 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003005
3006 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003007 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003008 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003009 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3010
3011 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003012 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003013 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003014 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3015
3016 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003017 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3018 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003019 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003020 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003021 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003022 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003023 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3024
3025 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003026 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003027 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003028 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3029
3030 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003031 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3032 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003033 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003034 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003035 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003036 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003037 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3038
3039 window->assertNoEvents();
3040}
3041
Gang Wange9087892020-01-07 12:17:14 -05003042TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003043 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003044 sp<FakeWindowHandle> window =
3045 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3046
3047 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003048 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003049
Arthur Hung72d8dc32020-03-28 00:48:39 +00003050 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003051 setFocusedWindow(window);
3052
Gang Wange9087892020-01-07 12:17:14 -05003053 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3054
3055 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3056 mDispatcher->notifyKey(&keyArgs);
3057
3058 InputEvent* event = window->consume();
3059 ASSERT_NE(event, nullptr);
3060
3061 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3062 ASSERT_NE(verified, nullptr);
3063 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3064
3065 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3066 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3067 ASSERT_EQ(keyArgs.source, verified->source);
3068 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3069
3070 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3071
3072 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003073 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003074 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003075 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3076 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3077 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3078 ASSERT_EQ(0, verifiedKey.repeatCount);
3079}
3080
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003081TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003082 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003083 sp<FakeWindowHandle> window =
3084 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3085
3086 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3087
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003088 ui::Transform transform;
3089 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3090
3091 gui::DisplayInfo displayInfo;
3092 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3093 displayInfo.transform = transform;
3094
3095 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003096
3097 NotifyMotionArgs motionArgs =
3098 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3099 ADISPLAY_ID_DEFAULT);
3100 mDispatcher->notifyMotion(&motionArgs);
3101
3102 InputEvent* event = window->consume();
3103 ASSERT_NE(event, nullptr);
3104
3105 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3106 ASSERT_NE(verified, nullptr);
3107 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3108
3109 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3110 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3111 EXPECT_EQ(motionArgs.source, verified->source);
3112 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3113
3114 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3115
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003116 const vec2 rawXY =
3117 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3118 motionArgs.pointerCoords[0].getXYValue());
3119 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3120 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003121 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003122 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003123 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003124 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3125 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3126}
3127
chaviw09c8d2d2020-08-24 15:48:26 -07003128/**
3129 * Ensure that separate calls to sign the same data are generating the same key.
3130 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3131 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3132 * tests.
3133 */
3134TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3135 KeyEvent event = getTestKeyEvent();
3136 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3137
3138 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3139 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3140 ASSERT_EQ(hmac1, hmac2);
3141}
3142
3143/**
3144 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3145 */
3146TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3147 KeyEvent event = getTestKeyEvent();
3148 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3149 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3150
3151 verifiedEvent.deviceId += 1;
3152 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3153
3154 verifiedEvent.source += 1;
3155 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3156
3157 verifiedEvent.eventTimeNanos += 1;
3158 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3159
3160 verifiedEvent.displayId += 1;
3161 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3162
3163 verifiedEvent.action += 1;
3164 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3165
3166 verifiedEvent.downTimeNanos += 1;
3167 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3168
3169 verifiedEvent.flags += 1;
3170 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3171
3172 verifiedEvent.keyCode += 1;
3173 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3174
3175 verifiedEvent.scanCode += 1;
3176 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3177
3178 verifiedEvent.metaState += 1;
3179 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3180
3181 verifiedEvent.repeatCount += 1;
3182 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3183}
3184
Vishnu Nair958da932020-08-21 17:12:37 -07003185TEST_F(InputDispatcherTest, SetFocusedWindow) {
3186 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3187 sp<FakeWindowHandle> windowTop =
3188 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3189 sp<FakeWindowHandle> windowSecond =
3190 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3191 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3192
3193 // Top window is also focusable but is not granted focus.
3194 windowTop->setFocusable(true);
3195 windowSecond->setFocusable(true);
3196 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3197 setFocusedWindow(windowSecond);
3198
3199 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003200 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3201 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003202
3203 // Focused window should receive event.
3204 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3205 windowTop->assertNoEvents();
3206}
3207
3208TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3209 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3210 sp<FakeWindowHandle> window =
3211 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3212 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3213
3214 window->setFocusable(true);
3215 // Release channel for window is no longer valid.
3216 window->releaseChannel();
3217 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3218 setFocusedWindow(window);
3219
3220 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003221 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3222 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003223
3224 // window channel is invalid, so it should not receive any input event.
3225 window->assertNoEvents();
3226}
3227
3228TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3229 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3230 sp<FakeWindowHandle> window =
3231 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3232 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3233
3234 // Window is not focusable.
3235 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3236 setFocusedWindow(window);
3237
3238 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003239 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3240 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003241
3242 // window is invalid, so it should not receive any input event.
3243 window->assertNoEvents();
3244}
3245
3246TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3247 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3248 sp<FakeWindowHandle> windowTop =
3249 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3250 sp<FakeWindowHandle> windowSecond =
3251 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3252 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3253
3254 windowTop->setFocusable(true);
3255 windowSecond->setFocusable(true);
3256 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3257 setFocusedWindow(windowTop);
3258 windowTop->consumeFocusEvent(true);
3259
3260 setFocusedWindow(windowSecond, windowTop);
3261 windowSecond->consumeFocusEvent(true);
3262 windowTop->consumeFocusEvent(false);
3263
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003264 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3265 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003266
3267 // Focused window should receive event.
3268 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3269}
3270
3271TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3272 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3273 sp<FakeWindowHandle> windowTop =
3274 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3275 sp<FakeWindowHandle> windowSecond =
3276 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3277 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3278
3279 windowTop->setFocusable(true);
3280 windowSecond->setFocusable(true);
3281 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3282 setFocusedWindow(windowSecond, windowTop);
3283
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003284 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3285 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003286
3287 // Event should be dropped.
3288 windowTop->assertNoEvents();
3289 windowSecond->assertNoEvents();
3290}
3291
3292TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3293 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3294 sp<FakeWindowHandle> window =
3295 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3296 sp<FakeWindowHandle> previousFocusedWindow =
3297 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3298 ADISPLAY_ID_DEFAULT);
3299 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3300
3301 window->setFocusable(true);
3302 previousFocusedWindow->setFocusable(true);
3303 window->setVisible(false);
3304 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3305 setFocusedWindow(previousFocusedWindow);
3306 previousFocusedWindow->consumeFocusEvent(true);
3307
3308 // Requesting focus on invisible window takes focus from currently focused window.
3309 setFocusedWindow(window);
3310 previousFocusedWindow->consumeFocusEvent(false);
3311
3312 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003313 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003314 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003315 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003316
3317 // Window does not get focus event or key down.
3318 window->assertNoEvents();
3319
3320 // Window becomes visible.
3321 window->setVisible(true);
3322 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3323
3324 // Window receives focus event.
3325 window->consumeFocusEvent(true);
3326 // Focused window receives key down.
3327 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3328}
3329
Vishnu Nair599f1412021-06-21 10:39:58 -07003330TEST_F(InputDispatcherTest, DisplayRemoved) {
3331 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3332 sp<FakeWindowHandle> window =
3333 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3334 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3335
3336 // window is granted focus.
3337 window->setFocusable(true);
3338 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3339 setFocusedWindow(window);
3340 window->consumeFocusEvent(true);
3341
3342 // When a display is removed window loses focus.
3343 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3344 window->consumeFocusEvent(false);
3345}
3346
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003347/**
3348 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3349 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3350 * of the 'slipperyEnterWindow'.
3351 *
3352 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3353 * a way so that the touched location is no longer covered by the top window.
3354 *
3355 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3356 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3357 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3358 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3359 * with ACTION_DOWN).
3360 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3361 * window moved itself away from the touched location and had Flag::SLIPPERY.
3362 *
3363 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3364 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3365 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3366 *
3367 * In this test, we ensure that the event received by the bottom window has
3368 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3369 */
3370TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3371 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3372 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3373
3374 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3375 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3376
3377 sp<FakeWindowHandle> slipperyExitWindow =
3378 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003379 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003380 // Make sure this one overlaps the bottom window
3381 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3382 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3383 // one. Windows with the same owner are not considered to be occluding each other.
3384 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3385
3386 sp<FakeWindowHandle> slipperyEnterWindow =
3387 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3388 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3389
3390 mDispatcher->setInputWindows(
3391 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3392
3393 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3394 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3395 ADISPLAY_ID_DEFAULT, {{50, 50}});
3396 mDispatcher->notifyMotion(&args);
3397 slipperyExitWindow->consumeMotionDown();
3398 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3399 mDispatcher->setInputWindows(
3400 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3401
3402 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3403 ADISPLAY_ID_DEFAULT, {{51, 51}});
3404 mDispatcher->notifyMotion(&args);
3405
3406 slipperyExitWindow->consumeMotionCancel();
3407
3408 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3409 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3410}
3411
Garfield Tan1c7bc862020-01-28 13:24:04 -08003412class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3413protected:
3414 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3415 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3416
Chris Yea209fde2020-07-22 13:54:51 -07003417 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003418 sp<FakeWindowHandle> mWindow;
3419
3420 virtual void SetUp() override {
3421 mFakePolicy = new FakeInputDispatcherPolicy();
3422 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003423 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003424 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3425 ASSERT_EQ(OK, mDispatcher->start());
3426
3427 setUpWindow();
3428 }
3429
3430 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003431 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003432 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3433
Vishnu Nair47074b82020-08-14 11:54:47 -07003434 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003435 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003436 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003437 mWindow->consumeFocusEvent(true);
3438 }
3439
Chris Ye2ad95392020-09-01 13:44:44 -07003440 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003441 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003442 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003443 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3444 mDispatcher->notifyKey(&keyArgs);
3445
3446 // Window should receive key down event.
3447 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3448 }
3449
3450 void expectKeyRepeatOnce(int32_t repeatCount) {
3451 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3452 InputEvent* repeatEvent = mWindow->consume();
3453 ASSERT_NE(nullptr, repeatEvent);
3454
3455 uint32_t eventType = repeatEvent->getType();
3456 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3457
3458 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3459 uint32_t eventAction = repeatKeyEvent->getAction();
3460 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3461 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3462 }
3463
Chris Ye2ad95392020-09-01 13:44:44 -07003464 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003465 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003466 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003467 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3468 mDispatcher->notifyKey(&keyArgs);
3469
3470 // Window should receive key down event.
3471 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3472 0 /*expectedFlags*/);
3473 }
3474};
3475
3476TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003477 sendAndConsumeKeyDown(1 /* deviceId */);
3478 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3479 expectKeyRepeatOnce(repeatCount);
3480 }
3481}
3482
3483TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3484 sendAndConsumeKeyDown(1 /* deviceId */);
3485 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3486 expectKeyRepeatOnce(repeatCount);
3487 }
3488 sendAndConsumeKeyDown(2 /* deviceId */);
3489 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003490 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3491 expectKeyRepeatOnce(repeatCount);
3492 }
3493}
3494
3495TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003496 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003497 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003498 sendAndConsumeKeyUp(1 /* deviceId */);
3499 mWindow->assertNoEvents();
3500}
3501
3502TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3503 sendAndConsumeKeyDown(1 /* deviceId */);
3504 expectKeyRepeatOnce(1 /*repeatCount*/);
3505 sendAndConsumeKeyDown(2 /* deviceId */);
3506 expectKeyRepeatOnce(1 /*repeatCount*/);
3507 // Stale key up from device 1.
3508 sendAndConsumeKeyUp(1 /* deviceId */);
3509 // Device 2 is still down, keep repeating
3510 expectKeyRepeatOnce(2 /*repeatCount*/);
3511 expectKeyRepeatOnce(3 /*repeatCount*/);
3512 // Device 2 key up
3513 sendAndConsumeKeyUp(2 /* deviceId */);
3514 mWindow->assertNoEvents();
3515}
3516
3517TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3518 sendAndConsumeKeyDown(1 /* deviceId */);
3519 expectKeyRepeatOnce(1 /*repeatCount*/);
3520 sendAndConsumeKeyDown(2 /* deviceId */);
3521 expectKeyRepeatOnce(1 /*repeatCount*/);
3522 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3523 sendAndConsumeKeyUp(2 /* deviceId */);
3524 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003525 mWindow->assertNoEvents();
3526}
3527
liushenxiang42232912021-05-21 20:24:09 +08003528TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3529 sendAndConsumeKeyDown(DEVICE_ID);
3530 expectKeyRepeatOnce(1 /*repeatCount*/);
3531 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3532 mDispatcher->notifyDeviceReset(&args);
3533 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3534 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3535 mWindow->assertNoEvents();
3536}
3537
Garfield Tan1c7bc862020-01-28 13:24:04 -08003538TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003539 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003540 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3541 InputEvent* repeatEvent = mWindow->consume();
3542 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3543 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3544 IdGenerator::getSource(repeatEvent->getId()));
3545 }
3546}
3547
3548TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003549 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003550
3551 std::unordered_set<int32_t> idSet;
3552 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3553 InputEvent* repeatEvent = mWindow->consume();
3554 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3555 int32_t id = repeatEvent->getId();
3556 EXPECT_EQ(idSet.end(), idSet.find(id));
3557 idSet.insert(id);
3558 }
3559}
3560
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003561/* Test InputDispatcher for MultiDisplay */
3562class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3563public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003564 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003565 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003566
Chris Yea209fde2020-07-22 13:54:51 -07003567 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003568 windowInPrimary =
3569 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003570
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003571 // Set focus window for primary display, but focused display would be second one.
3572 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003573 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003574 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003575 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003576 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003577
Chris Yea209fde2020-07-22 13:54:51 -07003578 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003579 windowInSecondary =
3580 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003581 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003582 // Set focus display to second one.
3583 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3584 // Set focus window for second display.
3585 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003586 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003587 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003588 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003589 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003590 }
3591
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003592 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003593 InputDispatcherTest::TearDown();
3594
Chris Yea209fde2020-07-22 13:54:51 -07003595 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003596 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003597 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003598 windowInSecondary.clear();
3599 }
3600
3601protected:
Chris Yea209fde2020-07-22 13:54:51 -07003602 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003603 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003604 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003605 sp<FakeWindowHandle> windowInSecondary;
3606};
3607
3608TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3609 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003610 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3611 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3612 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003613 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003614 windowInSecondary->assertNoEvents();
3615
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003616 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003617 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3618 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3619 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003620 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003621 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003622}
3623
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003624TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003625 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003626 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3627 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003628 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003629 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003630 windowInSecondary->assertNoEvents();
3631
3632 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003633 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003634 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003635 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003636 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003637
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003638 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003639 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003640
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003641 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003642 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3643 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003644
3645 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003646 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003647 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003648 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003649 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003650 windowInSecondary->assertNoEvents();
3651}
3652
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003653// Test per-display input monitors for motion event.
3654TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003655 FakeMonitorReceiver monitorInPrimary =
3656 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3657 FakeMonitorReceiver monitorInSecondary =
3658 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003659
3660 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003661 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3662 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3663 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003664 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003665 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003666 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003667 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003668
3669 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003670 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3671 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3672 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003673 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003674 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003675 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003676 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003677
3678 // Test inject a non-pointer motion event.
3679 // If specific a display, it will dispatch to the focused window of particular display,
3680 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003681 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3682 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3683 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003684 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003685 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003686 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003687 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003688}
3689
3690// Test per-display input monitors for key event.
3691TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003692 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003693 FakeMonitorReceiver monitorInPrimary =
3694 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3695 FakeMonitorReceiver monitorInSecondary =
3696 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003697
3698 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003699 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3700 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003701 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003702 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003703 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003704 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003705}
3706
Vishnu Nair958da932020-08-21 17:12:37 -07003707TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3708 sp<FakeWindowHandle> secondWindowInPrimary =
3709 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3710 secondWindowInPrimary->setFocusable(true);
3711 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3712 setFocusedWindow(secondWindowInPrimary);
3713 windowInPrimary->consumeFocusEvent(false);
3714 secondWindowInPrimary->consumeFocusEvent(true);
3715
3716 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003717 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3718 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003719 windowInPrimary->assertNoEvents();
3720 windowInSecondary->assertNoEvents();
3721 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3722}
3723
Arthur Hungdfd528e2021-12-08 13:23:04 +00003724TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3725 FakeMonitorReceiver monitorInPrimary =
3726 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3727 FakeMonitorReceiver monitorInSecondary =
3728 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3729
3730 // Test touch down on primary display.
3731 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3732 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3733 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3734 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3735 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3736
3737 // Test touch down on second display.
3738 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3739 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3740 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3741 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3742 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3743
3744 // Trigger cancel touch.
3745 mDispatcher->cancelCurrentTouch();
3746 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3747 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3748 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3749 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3750
3751 // Test inject a move motion event, no window/monitor should receive the event.
3752 ASSERT_EQ(InputEventInjectionResult::FAILED,
3753 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3754 ADISPLAY_ID_DEFAULT, {110, 200}))
3755 << "Inject motion event should return InputEventInjectionResult::FAILED";
3756 windowInPrimary->assertNoEvents();
3757 monitorInPrimary.assertNoEvents();
3758
3759 ASSERT_EQ(InputEventInjectionResult::FAILED,
3760 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3761 SECOND_DISPLAY_ID, {110, 200}))
3762 << "Inject motion event should return InputEventInjectionResult::FAILED";
3763 windowInSecondary->assertNoEvents();
3764 monitorInSecondary.assertNoEvents();
3765}
3766
Jackal Guof9696682018-10-05 12:23:23 +08003767class InputFilterTest : public InputDispatcherTest {
3768protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003769 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3770 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003771 NotifyMotionArgs motionArgs;
3772
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003773 motionArgs =
3774 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003775 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003776 motionArgs =
3777 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003778 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003779 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003780 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003781 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3782 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003783 } else {
3784 mFakePolicy->assertFilterInputEventWasNotCalled();
3785 }
3786 }
3787
3788 void testNotifyKey(bool expectToBeFiltered) {
3789 NotifyKeyArgs keyArgs;
3790
3791 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3792 mDispatcher->notifyKey(&keyArgs);
3793 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3794 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003795 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003796
3797 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003798 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003799 } else {
3800 mFakePolicy->assertFilterInputEventWasNotCalled();
3801 }
3802 }
3803};
3804
3805// Test InputFilter for MotionEvent
3806TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3807 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3808 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3809 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3810
3811 // Enable InputFilter
3812 mDispatcher->setInputFilterEnabled(true);
3813 // Test touch on both primary and second display, and check if both events are filtered.
3814 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3815 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3816
3817 // Disable InputFilter
3818 mDispatcher->setInputFilterEnabled(false);
3819 // Test touch on both primary and second display, and check if both events aren't filtered.
3820 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3821 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3822}
3823
3824// Test InputFilter for KeyEvent
3825TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3826 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3827 testNotifyKey(/*expectToBeFiltered*/ false);
3828
3829 // Enable InputFilter
3830 mDispatcher->setInputFilterEnabled(true);
3831 // Send a key event, and check if it is filtered.
3832 testNotifyKey(/*expectToBeFiltered*/ true);
3833
3834 // Disable InputFilter
3835 mDispatcher->setInputFilterEnabled(false);
3836 // Send a key event, and check if it isn't filtered.
3837 testNotifyKey(/*expectToBeFiltered*/ false);
3838}
3839
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003840// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3841// logical display coordinate space.
3842TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3843 ui::Transform firstDisplayTransform;
3844 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3845 ui::Transform secondDisplayTransform;
3846 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3847
3848 std::vector<gui::DisplayInfo> displayInfos(2);
3849 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3850 displayInfos[0].transform = firstDisplayTransform;
3851 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3852 displayInfos[1].transform = secondDisplayTransform;
3853
3854 mDispatcher->onWindowInfosChanged({}, displayInfos);
3855
3856 // Enable InputFilter
3857 mDispatcher->setInputFilterEnabled(true);
3858
3859 // Ensure the correct transforms are used for the displays.
3860 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3861 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3862}
3863
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003864class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3865protected:
3866 virtual void SetUp() override {
3867 InputDispatcherTest::SetUp();
3868
3869 /**
3870 * We don't need to enable input filter to test the injected event policy, but we enabled it
3871 * here to make the tests more realistic, since this policy only matters when inputfilter is
3872 * on.
3873 */
3874 mDispatcher->setInputFilterEnabled(true);
3875
3876 std::shared_ptr<InputApplicationHandle> application =
3877 std::make_shared<FakeApplicationHandle>();
3878 mWindow =
3879 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3880
3881 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3882 mWindow->setFocusable(true);
3883 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3884 setFocusedWindow(mWindow);
3885 mWindow->consumeFocusEvent(true);
3886 }
3887
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003888 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3889 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003890 KeyEvent event;
3891
3892 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3893 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3894 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3895 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3896 const int32_t additionalPolicyFlags =
3897 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3898 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3899 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3900 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3901 policyFlags | additionalPolicyFlags));
3902
3903 InputEvent* received = mWindow->consume();
3904 ASSERT_NE(nullptr, received);
3905 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003906 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3907 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3908 ASSERT_EQ(flags, keyEvent.getFlags());
3909 }
3910
3911 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3912 int32_t flags) {
3913 MotionEvent event;
3914 PointerProperties pointerProperties[1];
3915 PointerCoords pointerCoords[1];
3916 pointerProperties[0].clear();
3917 pointerProperties[0].id = 0;
3918 pointerCoords[0].clear();
3919 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3920 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3921
3922 ui::Transform identityTransform;
3923 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3924 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3925 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3926 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3927 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003928 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003929 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003930 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3931
3932 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3933 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3934 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3935 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3936 policyFlags | additionalPolicyFlags));
3937
3938 InputEvent* received = mWindow->consume();
3939 ASSERT_NE(nullptr, received);
3940 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3941 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3942 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3943 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003944 }
3945
3946private:
3947 sp<FakeWindowHandle> mWindow;
3948};
3949
3950TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003951 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3952 // filter. Without it, the event will no different from a regularly injected event, and the
3953 // injected device id will be overwritten.
3954 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3955 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003956}
3957
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003958TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003959 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003960 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3961 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3962}
3963
3964TEST_F(InputFilterInjectionPolicyTest,
3965 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3966 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3967 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3968 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003969}
3970
3971TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3972 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003973 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003974}
3975
chaviwfd6d3512019-03-25 13:23:49 -07003976class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003977 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003978 InputDispatcherTest::SetUp();
3979
Chris Yea209fde2020-07-22 13:54:51 -07003980 std::shared_ptr<FakeApplicationHandle> application =
3981 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003982 mUnfocusedWindow =
3983 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003984 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3985 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3986 // window.
chaviw3277faf2021-05-19 16:45:23 -05003987 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003988
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003989 mFocusedWindow =
3990 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3991 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05003992 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003993
3994 // Set focused application.
3995 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003996 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003997
3998 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003999 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004000 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004001 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004002 }
4003
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004004 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004005 InputDispatcherTest::TearDown();
4006
4007 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004008 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004009 }
4010
4011protected:
4012 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004013 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004014 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004015};
4016
4017// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4018// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4019// the onPointerDownOutsideFocus callback.
4020TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004021 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004022 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4023 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004024 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004025 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004026
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004027 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004028 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4029}
4030
4031// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4032// DOWN on the window that doesn't have focus. Ensure no window received the
4033// onPointerDownOutsideFocus callback.
4034TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004035 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004036 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004037 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004038 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004039
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004040 ASSERT_TRUE(mDispatcher->waitForIdle());
4041 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004042}
4043
4044// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4045// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4046TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004047 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4048 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004049 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004050 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004051
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004052 ASSERT_TRUE(mDispatcher->waitForIdle());
4053 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004054}
4055
4056// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4057// DOWN on the window that already has focus. Ensure no window received the
4058// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004059TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004060 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004061 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004062 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004063 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004064 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004065
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004066 ASSERT_TRUE(mDispatcher->waitForIdle());
4067 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004068}
4069
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004070// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4071// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4072TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4073 const MotionEvent event =
4074 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4075 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4076 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4077 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4078 .build();
4079 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4080 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4081 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4082
4083 ASSERT_TRUE(mDispatcher->waitForIdle());
4084 mFakePolicy->assertOnPointerDownWasNotCalled();
4085 // Ensure that the unfocused window did not receive any FOCUS events.
4086 mUnfocusedWindow->assertNoEvents();
4087}
4088
chaviwaf87b3e2019-10-01 16:59:28 -07004089// These tests ensures we can send touch events to a single client when there are multiple input
4090// windows that point to the same client token.
4091class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4092 virtual void SetUp() override {
4093 InputDispatcherTest::SetUp();
4094
Chris Yea209fde2020-07-22 13:54:51 -07004095 std::shared_ptr<FakeApplicationHandle> application =
4096 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004097 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4098 ADISPLAY_ID_DEFAULT);
4099 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
4100 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05004101 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004102 mWindow1->setFrame(Rect(0, 0, 100, 100));
4103
4104 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4105 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05004106 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004107 mWindow2->setFrame(Rect(100, 100, 200, 200));
4108
Arthur Hung72d8dc32020-03-28 00:48:39 +00004109 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004110 }
4111
4112protected:
4113 sp<FakeWindowHandle> mWindow1;
4114 sp<FakeWindowHandle> mWindow2;
4115
4116 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004117 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004118 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4119 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004120 }
4121
4122 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4123 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004124 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004125 InputEvent* event = window->consume();
4126
4127 ASSERT_NE(nullptr, event) << name.c_str()
4128 << ": consumer should have returned non-NULL event.";
4129
4130 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4131 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4132 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4133
4134 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004135 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004136
4137 for (size_t i = 0; i < points.size(); i++) {
4138 float expectedX = points[i].x;
4139 float expectedY = points[i].y;
4140
4141 EXPECT_EQ(expectedX, motionEvent.getX(i))
4142 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4143 << ", got " << motionEvent.getX(i);
4144 EXPECT_EQ(expectedY, motionEvent.getY(i))
4145 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4146 << ", got " << motionEvent.getY(i);
4147 }
4148 }
chaviw9eaa22c2020-07-01 16:21:27 -07004149
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004150 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004151 std::vector<PointF> expectedPoints) {
4152 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4153 ADISPLAY_ID_DEFAULT, touchedPoints);
4154 mDispatcher->notifyMotion(&motionArgs);
4155
4156 // Always consume from window1 since it's the window that has the InputReceiver
4157 consumeMotionEvent(mWindow1, action, expectedPoints);
4158 }
chaviwaf87b3e2019-10-01 16:59:28 -07004159};
4160
4161TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4162 // Touch Window 1
4163 PointF touchedPoint = {10, 10};
4164 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004165 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004166
4167 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004168 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004169
4170 // Touch Window 2
4171 touchedPoint = {150, 150};
4172 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004173 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004174}
4175
chaviw9eaa22c2020-07-01 16:21:27 -07004176TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4177 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004178 mWindow2->setWindowScale(0.5f, 0.5f);
4179
4180 // Touch Window 1
4181 PointF touchedPoint = {10, 10};
4182 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004183 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004184 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004185 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004186
4187 // Touch Window 2
4188 touchedPoint = {150, 150};
4189 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004190 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4191 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004192
chaviw9eaa22c2020-07-01 16:21:27 -07004193 // Update the transform so rotation is set
4194 mWindow2->setWindowTransform(0, -1, 1, 0);
4195 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4196 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004197}
4198
chaviw9eaa22c2020-07-01 16:21:27 -07004199TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004200 mWindow2->setWindowScale(0.5f, 0.5f);
4201
4202 // Touch Window 1
4203 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4204 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004205 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004206
4207 // Touch Window 2
4208 int32_t actionPointerDown =
4209 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004210 touchedPoints.push_back(PointF{150, 150});
4211 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4212 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004213
chaviw9eaa22c2020-07-01 16:21:27 -07004214 // Release Window 2
4215 int32_t actionPointerUp =
4216 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4217 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4218 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004219
chaviw9eaa22c2020-07-01 16:21:27 -07004220 // Update the transform so rotation is set for Window 2
4221 mWindow2->setWindowTransform(0, -1, 1, 0);
4222 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4223 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004224}
4225
chaviw9eaa22c2020-07-01 16:21:27 -07004226TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004227 mWindow2->setWindowScale(0.5f, 0.5f);
4228
4229 // Touch Window 1
4230 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4231 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004232 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004233
4234 // Touch Window 2
4235 int32_t actionPointerDown =
4236 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004237 touchedPoints.push_back(PointF{150, 150});
4238 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004239
chaviw9eaa22c2020-07-01 16:21:27 -07004240 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004241
4242 // Move both windows
4243 touchedPoints = {{20, 20}, {175, 175}};
4244 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4245 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4246
chaviw9eaa22c2020-07-01 16:21:27 -07004247 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004248
chaviw9eaa22c2020-07-01 16:21:27 -07004249 // Release Window 2
4250 int32_t actionPointerUp =
4251 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4252 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4253 expectedPoints.pop_back();
4254
4255 // Touch Window 2
4256 mWindow2->setWindowTransform(0, -1, 1, 0);
4257 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4258 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4259
4260 // Move both windows
4261 touchedPoints = {{20, 20}, {175, 175}};
4262 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4263 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4264
4265 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004266}
4267
4268TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4269 mWindow1->setWindowScale(0.5f, 0.5f);
4270
4271 // Touch Window 1
4272 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4273 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004274 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004275
4276 // Touch Window 2
4277 int32_t actionPointerDown =
4278 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004279 touchedPoints.push_back(PointF{150, 150});
4280 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004281
chaviw9eaa22c2020-07-01 16:21:27 -07004282 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004283
4284 // Move both windows
4285 touchedPoints = {{20, 20}, {175, 175}};
4286 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4287 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4288
chaviw9eaa22c2020-07-01 16:21:27 -07004289 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004290}
4291
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004292class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4293 virtual void SetUp() override {
4294 InputDispatcherTest::SetUp();
4295
Chris Yea209fde2020-07-22 13:54:51 -07004296 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004297 mApplication->setDispatchingTimeout(20ms);
4298 mWindow =
4299 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4300 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004301 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004302 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004303 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4304 // window.
chaviw3277faf2021-05-19 16:45:23 -05004305 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004306
4307 // Set focused application.
4308 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4309
4310 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004311 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004312 mWindow->consumeFocusEvent(true);
4313 }
4314
4315 virtual void TearDown() override {
4316 InputDispatcherTest::TearDown();
4317 mWindow.clear();
4318 }
4319
4320protected:
Chris Yea209fde2020-07-22 13:54:51 -07004321 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004322 sp<FakeWindowHandle> mWindow;
4323 static constexpr PointF WINDOW_LOCATION = {20, 20};
4324
4325 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004326 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004327 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4328 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004329 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004330 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4331 WINDOW_LOCATION));
4332 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004333
4334 sp<FakeWindowHandle> addSpyWindow() {
4335 sp<FakeWindowHandle> spy =
4336 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4337 spy->setTrustedOverlay(true);
4338 spy->setFocusable(false);
4339 spy->setInputFeatures(WindowInfo::Feature::SPY);
4340 spy->setDispatchingTimeout(30ms);
4341 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4342 return spy;
4343 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004344};
4345
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004346// Send a tap and respond, which should not cause an ANR.
4347TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4348 tapOnWindow();
4349 mWindow->consumeMotionDown();
4350 mWindow->consumeMotionUp();
4351 ASSERT_TRUE(mDispatcher->waitForIdle());
4352 mFakePolicy->assertNotifyAnrWasNotCalled();
4353}
4354
4355// Send a regular key and respond, which should not cause an ANR.
4356TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004357 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004358 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4359 ASSERT_TRUE(mDispatcher->waitForIdle());
4360 mFakePolicy->assertNotifyAnrWasNotCalled();
4361}
4362
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004363TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4364 mWindow->setFocusable(false);
4365 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4366 mWindow->consumeFocusEvent(false);
4367
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004368 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004369 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004370 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4371 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004372 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004373 // Key will not go to window because we have no focused window.
4374 // The 'no focused window' ANR timer should start instead.
4375
4376 // Now, the focused application goes away.
4377 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4378 // The key should get dropped and there should be no ANR.
4379
4380 ASSERT_TRUE(mDispatcher->waitForIdle());
4381 mFakePolicy->assertNotifyAnrWasNotCalled();
4382}
4383
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004384// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004385// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4386// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004387TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004388 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004389 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4390 WINDOW_LOCATION));
4391
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004392 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4393 ASSERT_TRUE(sequenceNum);
4394 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004395 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004396
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004397 mWindow->finishEvent(*sequenceNum);
4398 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4399 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004400 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004401 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004402}
4403
4404// Send a key to the app and have the app not respond right away.
4405TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4406 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004407 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004408 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4409 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004410 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004411 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004412 ASSERT_TRUE(mDispatcher->waitForIdle());
4413}
4414
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004415// We have a focused application, but no focused window
4416TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004417 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004418 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4419 mWindow->consumeFocusEvent(false);
4420
4421 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004422 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004423 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4424 WINDOW_LOCATION));
4425 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4426 mDispatcher->waitForIdle();
4427 mFakePolicy->assertNotifyAnrWasNotCalled();
4428
4429 // Once a focused event arrives, we get an ANR for this application
4430 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4431 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004432 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004433 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004434 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004435 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004436 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004437 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004438 ASSERT_TRUE(mDispatcher->waitForIdle());
4439}
4440
4441// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004442// Make sure that we don't notify policy twice about the same ANR.
4443TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004444 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004445 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4446 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004447
4448 // Once a focused event arrives, we get an ANR for this application
4449 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4450 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004451 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004452 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004453 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004454 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004455 const std::chrono::duration appTimeout =
4456 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004457 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004458
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004459 std::this_thread::sleep_for(appTimeout);
4460 // ANR should not be raised again. It is up to policy to do that if it desires.
4461 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004462
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004463 // If we now get a focused window, the ANR should stop, but the policy handles that via
4464 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004465 ASSERT_TRUE(mDispatcher->waitForIdle());
4466}
4467
4468// We have a focused application, but no focused window
4469TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004470 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004471 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4472 mWindow->consumeFocusEvent(false);
4473
4474 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004475 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004476 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004477 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4478 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004479
4480 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004481 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004482
4483 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004484 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004485 ASSERT_TRUE(mDispatcher->waitForIdle());
4486 mWindow->assertNoEvents();
4487}
4488
4489/**
4490 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4491 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4492 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4493 * the ANR mechanism should still work.
4494 *
4495 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4496 * DOWN event, while not responding on the second one.
4497 */
4498TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4499 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4500 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4501 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4502 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4503 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004504 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004505
4506 // Now send ACTION_UP, with identical timestamp
4507 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4508 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4509 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4510 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004511 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004512
4513 // We have now sent down and up. Let's consume first event and then ANR on the second.
4514 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4515 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004516 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004517}
4518
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004519// A spy window can receive an ANR
4520TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4521 sp<FakeWindowHandle> spy = addSpyWindow();
4522
4523 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4524 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4525 WINDOW_LOCATION));
4526 mWindow->consumeMotionDown();
4527
4528 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4529 ASSERT_TRUE(sequenceNum);
4530 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4531 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy->getToken());
4532
4533 spy->finishEvent(*sequenceNum);
4534 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4535 0 /*flags*/);
4536 ASSERT_TRUE(mDispatcher->waitForIdle());
4537 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken());
4538}
4539
4540// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004541// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004542TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4543 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004544
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004545 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4546 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004547 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004548 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004549
4550 // Stuck on the ACTION_UP
4551 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004552 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004553
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004554 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004555 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004556 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4557 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004558
4559 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4560 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004561 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004562 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004563 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004564}
4565
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004566// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004567// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004568TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4569 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004570
4571 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004572 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4573 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004574
4575 mWindow->consumeMotionDown();
4576 // Stuck on the ACTION_UP
4577 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004578 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004579
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004580 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004581 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004582 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4583 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004584
4585 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4586 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004587 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004588 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004589 spy->assertNoEvents();
4590}
4591
4592TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4593 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4594
4595 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4596
4597 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4598 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4599 WINDOW_LOCATION));
4600
4601 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4602 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4603 ASSERT_TRUE(consumeSeq);
4604
4605 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(30ms);
4606
4607 monitor.finishEvent(*consumeSeq);
4608 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4609
4610 ASSERT_TRUE(mDispatcher->waitForIdle());
4611 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004612}
4613
4614// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4615// process events, you don't get an anr. When the window later becomes unresponsive again, you
4616// get an ANR again.
4617// 1. tap -> block on ACTION_UP -> receive ANR
4618// 2. consume all pending events (= queue becomes healthy again)
4619// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4620TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4621 tapOnWindow();
4622
4623 mWindow->consumeMotionDown();
4624 // Block on ACTION_UP
4625 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004626 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004627 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4628 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004629 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004630 mWindow->assertNoEvents();
4631
4632 tapOnWindow();
4633 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004634 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004635 mWindow->consumeMotionUp();
4636
4637 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004638 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004639 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004640 mWindow->assertNoEvents();
4641}
4642
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004643// If a connection remains unresponsive for a while, make sure policy is only notified once about
4644// it.
4645TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004646 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004647 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4648 WINDOW_LOCATION));
4649
4650 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004651 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004652 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004653 // 'notifyConnectionUnresponsive' should only be called once per connection
4654 mFakePolicy->assertNotifyAnrWasNotCalled();
4655 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004656 mWindow->consumeMotionDown();
4657 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4658 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4659 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004660 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004661 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004662 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004663}
4664
4665/**
4666 * If a window is processing a motion event, and then a key event comes in, the key event should
4667 * not to to the focused window until the motion is processed.
4668 *
4669 * Warning!!!
4670 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4671 * and the injection timeout that we specify when injecting the key.
4672 * We must have the injection timeout (10ms) be smaller than
4673 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4674 *
4675 * If that value changes, this test should also change.
4676 */
4677TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4678 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4679 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4680
4681 tapOnWindow();
4682 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4683 ASSERT_TRUE(downSequenceNum);
4684 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4685 ASSERT_TRUE(upSequenceNum);
4686 // Don't finish the events yet, and send a key
4687 // Injection will "succeed" because we will eventually give up and send the key to the focused
4688 // window even if motions are still being processed. But because the injection timeout is short,
4689 // we will receive INJECTION_TIMED_OUT as the result.
4690
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004691 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004692 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004693 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4694 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004695 // Key will not be sent to the window, yet, because the window is still processing events
4696 // and the key remains pending, waiting for the touch events to be processed
4697 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4698 ASSERT_FALSE(keySequenceNum);
4699
4700 std::this_thread::sleep_for(500ms);
4701 // if we wait long enough though, dispatcher will give up, and still send the key
4702 // to the focused window, even though we have not yet finished the motion event
4703 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4704 mWindow->finishEvent(*downSequenceNum);
4705 mWindow->finishEvent(*upSequenceNum);
4706}
4707
4708/**
4709 * If a window is processing a motion event, and then a key event comes in, the key event should
4710 * not go to the focused window until the motion is processed.
4711 * If then a new motion comes in, then the pending key event should be going to the currently
4712 * focused window right away.
4713 */
4714TEST_F(InputDispatcherSingleWindowAnr,
4715 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4716 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4717 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4718
4719 tapOnWindow();
4720 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4721 ASSERT_TRUE(downSequenceNum);
4722 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4723 ASSERT_TRUE(upSequenceNum);
4724 // Don't finish the events yet, and send a key
4725 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004726 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004727 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004728 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004729 // At this point, key is still pending, and should not be sent to the application yet.
4730 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4731 ASSERT_FALSE(keySequenceNum);
4732
4733 // Now tap down again. It should cause the pending key to go to the focused window right away.
4734 tapOnWindow();
4735 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4736 // the other events yet. We can finish events in any order.
4737 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4738 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4739 mWindow->consumeMotionDown();
4740 mWindow->consumeMotionUp();
4741 mWindow->assertNoEvents();
4742}
4743
4744class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4745 virtual void SetUp() override {
4746 InputDispatcherTest::SetUp();
4747
Chris Yea209fde2020-07-22 13:54:51 -07004748 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004749 mApplication->setDispatchingTimeout(10ms);
4750 mUnfocusedWindow =
4751 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4752 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4753 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4754 // window.
4755 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004756 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4757 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4758 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004759
4760 mFocusedWindow =
4761 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004762 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004763 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004764 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004765
4766 // Set focused application.
4767 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004768 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004769
4770 // Expect one focus window exist in display.
4771 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004772 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004773 mFocusedWindow->consumeFocusEvent(true);
4774 }
4775
4776 virtual void TearDown() override {
4777 InputDispatcherTest::TearDown();
4778
4779 mUnfocusedWindow.clear();
4780 mFocusedWindow.clear();
4781 }
4782
4783protected:
Chris Yea209fde2020-07-22 13:54:51 -07004784 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004785 sp<FakeWindowHandle> mUnfocusedWindow;
4786 sp<FakeWindowHandle> mFocusedWindow;
4787 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4788 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4789 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4790
4791 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4792
4793 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4794
4795private:
4796 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004797 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004798 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4799 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004800 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004801 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4802 location));
4803 }
4804};
4805
4806// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4807// should be ANR'd first.
4808TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004809 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004810 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4811 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004812 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004813 mFocusedWindow->consumeMotionDown();
4814 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4815 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4816 // We consumed all events, so no ANR
4817 ASSERT_TRUE(mDispatcher->waitForIdle());
4818 mFakePolicy->assertNotifyAnrWasNotCalled();
4819
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004820 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004821 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4822 FOCUSED_WINDOW_LOCATION));
4823 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4824 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004825
4826 const std::chrono::duration timeout =
4827 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004828 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004829 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4830 // sequence to make it consistent
4831 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004832 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004833 mFocusedWindow->consumeMotionDown();
4834 // This cancel is generated because the connection was unresponsive
4835 mFocusedWindow->consumeMotionCancel();
4836 mFocusedWindow->assertNoEvents();
4837 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004838 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004839 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004840 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004841}
4842
4843// If we have 2 windows with identical timeouts that are both unresponsive,
4844// it doesn't matter which order they should have ANR.
4845// But we should receive ANR for both.
4846TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4847 // Set the timeout for unfocused window to match the focused window
4848 mUnfocusedWindow->setDispatchingTimeout(10ms);
4849 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4850
4851 tapOnFocusedWindow();
4852 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004853 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4854 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004855
4856 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004857 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4858 mFocusedWindow->getToken() == anrConnectionToken2);
4859 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4860 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004861
4862 ASSERT_TRUE(mDispatcher->waitForIdle());
4863 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004864
4865 mFocusedWindow->consumeMotionDown();
4866 mFocusedWindow->consumeMotionUp();
4867 mUnfocusedWindow->consumeMotionOutside();
4868
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004869 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4870 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004871
4872 // Both applications should be marked as responsive, in any order
4873 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4874 mFocusedWindow->getToken() == responsiveToken2);
4875 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4876 mUnfocusedWindow->getToken() == responsiveToken2);
4877 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004878}
4879
4880// If a window is already not responding, the second tap on the same window should be ignored.
4881// We should also log an error to account for the dropped event (not tested here).
4882// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4883TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4884 tapOnFocusedWindow();
4885 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4886 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4887 // Receive the events, but don't respond
4888 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4889 ASSERT_TRUE(downEventSequenceNum);
4890 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4891 ASSERT_TRUE(upEventSequenceNum);
4892 const std::chrono::duration timeout =
4893 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004894 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004895
4896 // Tap once again
4897 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004898 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004899 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4900 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004901 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004902 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4903 FOCUSED_WINDOW_LOCATION));
4904 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4905 // valid touch target
4906 mUnfocusedWindow->assertNoEvents();
4907
4908 // Consume the first tap
4909 mFocusedWindow->finishEvent(*downEventSequenceNum);
4910 mFocusedWindow->finishEvent(*upEventSequenceNum);
4911 ASSERT_TRUE(mDispatcher->waitForIdle());
4912 // The second tap did not go to the focused window
4913 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004914 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004915 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004916 mFakePolicy->assertNotifyAnrWasNotCalled();
4917}
4918
4919// If you tap outside of all windows, there will not be ANR
4920TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004921 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004922 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4923 LOCATION_OUTSIDE_ALL_WINDOWS));
4924 ASSERT_TRUE(mDispatcher->waitForIdle());
4925 mFakePolicy->assertNotifyAnrWasNotCalled();
4926}
4927
4928// Since the focused window is paused, tapping on it should not produce any events
4929TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4930 mFocusedWindow->setPaused(true);
4931 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4932
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004933 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004934 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4935 FOCUSED_WINDOW_LOCATION));
4936
4937 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4938 ASSERT_TRUE(mDispatcher->waitForIdle());
4939 // Should not ANR because the window is paused, and touches shouldn't go to it
4940 mFakePolicy->assertNotifyAnrWasNotCalled();
4941
4942 mFocusedWindow->assertNoEvents();
4943 mUnfocusedWindow->assertNoEvents();
4944}
4945
4946/**
4947 * If a window is processing a motion event, and then a key event comes in, the key event should
4948 * not to to the focused window until the motion is processed.
4949 * If a different window becomes focused at this time, the key should go to that window instead.
4950 *
4951 * Warning!!!
4952 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4953 * and the injection timeout that we specify when injecting the key.
4954 * We must have the injection timeout (10ms) be smaller than
4955 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4956 *
4957 * If that value changes, this test should also change.
4958 */
4959TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4960 // Set a long ANR timeout to prevent it from triggering
4961 mFocusedWindow->setDispatchingTimeout(2s);
4962 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4963
4964 tapOnUnfocusedWindow();
4965 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4966 ASSERT_TRUE(downSequenceNum);
4967 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4968 ASSERT_TRUE(upSequenceNum);
4969 // Don't finish the events yet, and send a key
4970 // Injection will succeed because we will eventually give up and send the key to the focused
4971 // window even if motions are still being processed.
4972
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004973 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004974 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004975 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4976 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004977 // Key will not be sent to the window, yet, because the window is still processing events
4978 // and the key remains pending, waiting for the touch events to be processed
4979 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4980 ASSERT_FALSE(keySequenceNum);
4981
4982 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004983 mFocusedWindow->setFocusable(false);
4984 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004985 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004986 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004987
4988 // Focus events should precede the key events
4989 mUnfocusedWindow->consumeFocusEvent(true);
4990 mFocusedWindow->consumeFocusEvent(false);
4991
4992 // Finish the tap events, which should unblock dispatcher
4993 mUnfocusedWindow->finishEvent(*downSequenceNum);
4994 mUnfocusedWindow->finishEvent(*upSequenceNum);
4995
4996 // Now that all queues are cleared and no backlog in the connections, the key event
4997 // can finally go to the newly focused "mUnfocusedWindow".
4998 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4999 mFocusedWindow->assertNoEvents();
5000 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005001 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005002}
5003
5004// When the touch stream is split across 2 windows, and one of them does not respond,
5005// then ANR should be raised and the touch should be canceled for the unresponsive window.
5006// The other window should not be affected by that.
5007TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5008 // Touch Window 1
5009 NotifyMotionArgs motionArgs =
5010 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5011 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5012 mDispatcher->notifyMotion(&motionArgs);
5013 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5014 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5015
5016 // Touch Window 2
5017 int32_t actionPointerDown =
5018 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
5019
5020 motionArgs =
5021 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5022 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
5023 mDispatcher->notifyMotion(&motionArgs);
5024
5025 const std::chrono::duration timeout =
5026 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005027 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005028
5029 mUnfocusedWindow->consumeMotionDown();
5030 mFocusedWindow->consumeMotionDown();
5031 // Focused window may or may not receive ACTION_MOVE
5032 // But it should definitely receive ACTION_CANCEL due to the ANR
5033 InputEvent* event;
5034 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5035 ASSERT_TRUE(moveOrCancelSequenceNum);
5036 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5037 ASSERT_NE(nullptr, event);
5038 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5039 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5040 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5041 mFocusedWindow->consumeMotionCancel();
5042 } else {
5043 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5044 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005045 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005046 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005047
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005048 mUnfocusedWindow->assertNoEvents();
5049 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005050 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005051}
5052
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005053/**
5054 * If we have no focused window, and a key comes in, we start the ANR timer.
5055 * The focused application should add a focused window before the timer runs out to prevent ANR.
5056 *
5057 * If the user touches another application during this time, the key should be dropped.
5058 * Next, if a new focused window comes in, without toggling the focused application,
5059 * then no ANR should occur.
5060 *
5061 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5062 * but in some cases the policy may not update the focused application.
5063 */
5064TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5065 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5066 std::make_shared<FakeApplicationHandle>();
5067 focusedApplication->setDispatchingTimeout(60ms);
5068 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5069 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5070 mFocusedWindow->setFocusable(false);
5071
5072 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5073 mFocusedWindow->consumeFocusEvent(false);
5074
5075 // Send a key. The ANR timer should start because there is no focused window.
5076 // 'focusedApplication' will get blamed if this timer completes.
5077 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005078 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005079 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005080 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5081 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005082 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005083
5084 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5085 // then the injected touches won't cause the focused event to get dropped.
5086 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5087 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5088 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5089 // For this test, it means that the key would get delivered to the window once it becomes
5090 // focused.
5091 std::this_thread::sleep_for(10ms);
5092
5093 // Touch unfocused window. This should force the pending key to get dropped.
5094 NotifyMotionArgs motionArgs =
5095 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5096 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5097 mDispatcher->notifyMotion(&motionArgs);
5098
5099 // We do not consume the motion right away, because that would require dispatcher to first
5100 // process (== drop) the key event, and by that time, ANR will be raised.
5101 // Set the focused window first.
5102 mFocusedWindow->setFocusable(true);
5103 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5104 setFocusedWindow(mFocusedWindow);
5105 mFocusedWindow->consumeFocusEvent(true);
5106 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5107 // to another application. This could be a bug / behaviour in the policy.
5108
5109 mUnfocusedWindow->consumeMotionDown();
5110
5111 ASSERT_TRUE(mDispatcher->waitForIdle());
5112 // Should not ANR because we actually have a focused window. It was just added too slowly.
5113 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5114}
5115
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005116// These tests ensure we cannot send touch events to a window that's positioned behind a window
5117// that has feature NO_INPUT_CHANNEL.
5118// Layout:
5119// Top (closest to user)
5120// mNoInputWindow (above all windows)
5121// mBottomWindow
5122// Bottom (furthest from user)
5123class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5124 virtual void SetUp() override {
5125 InputDispatcherTest::SetUp();
5126
5127 mApplication = std::make_shared<FakeApplicationHandle>();
5128 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5129 "Window without input channel", ADISPLAY_ID_DEFAULT,
5130 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5131
chaviw3277faf2021-05-19 16:45:23 -05005132 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005133 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5134 // It's perfectly valid for this window to not have an associated input channel
5135
5136 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5137 ADISPLAY_ID_DEFAULT);
5138 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5139
5140 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5141 }
5142
5143protected:
5144 std::shared_ptr<FakeApplicationHandle> mApplication;
5145 sp<FakeWindowHandle> mNoInputWindow;
5146 sp<FakeWindowHandle> mBottomWindow;
5147};
5148
5149TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5150 PointF touchedPoint = {10, 10};
5151
5152 NotifyMotionArgs motionArgs =
5153 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5154 ADISPLAY_ID_DEFAULT, {touchedPoint});
5155 mDispatcher->notifyMotion(&motionArgs);
5156
5157 mNoInputWindow->assertNoEvents();
5158 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5159 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5160 // and therefore should prevent mBottomWindow from receiving touches
5161 mBottomWindow->assertNoEvents();
5162}
5163
5164/**
5165 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5166 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5167 */
5168TEST_F(InputDispatcherMultiWindowOcclusionTests,
5169 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5170 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5171 "Window with input channel and NO_INPUT_CHANNEL",
5172 ADISPLAY_ID_DEFAULT);
5173
chaviw3277faf2021-05-19 16:45:23 -05005174 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005175 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5176 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5177
5178 PointF touchedPoint = {10, 10};
5179
5180 NotifyMotionArgs motionArgs =
5181 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5182 ADISPLAY_ID_DEFAULT, {touchedPoint});
5183 mDispatcher->notifyMotion(&motionArgs);
5184
5185 mNoInputWindow->assertNoEvents();
5186 mBottomWindow->assertNoEvents();
5187}
5188
Vishnu Nair958da932020-08-21 17:12:37 -07005189class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5190protected:
5191 std::shared_ptr<FakeApplicationHandle> mApp;
5192 sp<FakeWindowHandle> mWindow;
5193 sp<FakeWindowHandle> mMirror;
5194
5195 virtual void SetUp() override {
5196 InputDispatcherTest::SetUp();
5197 mApp = std::make_shared<FakeApplicationHandle>();
5198 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5199 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5200 mWindow->getToken());
5201 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5202 mWindow->setFocusable(true);
5203 mMirror->setFocusable(true);
5204 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5205 }
5206};
5207
5208TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5209 // Request focus on a mirrored window
5210 setFocusedWindow(mMirror);
5211
5212 // window gets focused
5213 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005214 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5215 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005216 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5217}
5218
5219// A focused & mirrored window remains focused only if the window and its mirror are both
5220// focusable.
5221TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5222 setFocusedWindow(mMirror);
5223
5224 // window gets focused
5225 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005226 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5227 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005228 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005229 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5230 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005231 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5232
5233 mMirror->setFocusable(false);
5234 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5235
5236 // window loses focus since one of the windows associated with the token in not focusable
5237 mWindow->consumeFocusEvent(false);
5238
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005239 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5240 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005241 mWindow->assertNoEvents();
5242}
5243
5244// A focused & mirrored window remains focused until the window and its mirror both become
5245// invisible.
5246TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5247 setFocusedWindow(mMirror);
5248
5249 // window gets focused
5250 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005251 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5252 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005253 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005254 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5255 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005256 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5257
5258 mMirror->setVisible(false);
5259 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5260
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005261 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5262 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005263 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005264 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5265 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005266 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5267
5268 mWindow->setVisible(false);
5269 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5270
5271 // window loses focus only after all windows associated with the token become invisible.
5272 mWindow->consumeFocusEvent(false);
5273
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005274 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5275 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005276 mWindow->assertNoEvents();
5277}
5278
5279// A focused & mirrored window remains focused until both windows are removed.
5280TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5281 setFocusedWindow(mMirror);
5282
5283 // window gets focused
5284 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005285 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5286 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005287 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005288 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5289 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005290 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5291
5292 // single window is removed but the window token remains focused
5293 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5294
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005295 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5296 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005297 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005298 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5299 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005300 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5301
5302 // Both windows are removed
5303 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5304 mWindow->consumeFocusEvent(false);
5305
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005306 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5307 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005308 mWindow->assertNoEvents();
5309}
5310
5311// Focus request can be pending until one window becomes visible.
5312TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5313 // Request focus on an invisible mirror.
5314 mWindow->setVisible(false);
5315 mMirror->setVisible(false);
5316 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5317 setFocusedWindow(mMirror);
5318
5319 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005320 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005321 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005322 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005323
5324 mMirror->setVisible(true);
5325 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5326
5327 // window gets focused
5328 mWindow->consumeFocusEvent(true);
5329 // window gets the pending key event
5330 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5331}
Prabir Pradhan99987712020-11-10 18:43:05 -08005332
5333class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5334protected:
5335 std::shared_ptr<FakeApplicationHandle> mApp;
5336 sp<FakeWindowHandle> mWindow;
5337 sp<FakeWindowHandle> mSecondWindow;
5338
5339 void SetUp() override {
5340 InputDispatcherTest::SetUp();
5341 mApp = std::make_shared<FakeApplicationHandle>();
5342 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5343 mWindow->setFocusable(true);
5344 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5345 mSecondWindow->setFocusable(true);
5346
5347 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5348 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5349
5350 setFocusedWindow(mWindow);
5351 mWindow->consumeFocusEvent(true);
5352 }
5353
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005354 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5355 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005356 mDispatcher->notifyPointerCaptureChanged(&args);
5357 }
5358
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005359 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5360 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005361 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005362 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5363 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005364 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005365 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005366 }
5367};
5368
5369TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5370 // Ensure that capture cannot be obtained for unfocused windows.
5371 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5372 mFakePolicy->assertSetPointerCaptureNotCalled();
5373 mSecondWindow->assertNoEvents();
5374
5375 // Ensure that capture can be enabled from the focus window.
5376 requestAndVerifyPointerCapture(mWindow, true);
5377
5378 // Ensure that capture cannot be disabled from a window that does not have capture.
5379 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5380 mFakePolicy->assertSetPointerCaptureNotCalled();
5381
5382 // Ensure that capture can be disabled from the window with capture.
5383 requestAndVerifyPointerCapture(mWindow, false);
5384}
5385
5386TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005387 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005388
5389 setFocusedWindow(mSecondWindow);
5390
5391 // Ensure that the capture disabled event was sent first.
5392 mWindow->consumeCaptureEvent(false);
5393 mWindow->consumeFocusEvent(false);
5394 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005395 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005396
5397 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005398 notifyPointerCaptureChanged({});
5399 notifyPointerCaptureChanged(request);
5400 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005401 mWindow->assertNoEvents();
5402 mSecondWindow->assertNoEvents();
5403 mFakePolicy->assertSetPointerCaptureNotCalled();
5404}
5405
5406TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005407 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005408
5409 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005410 notifyPointerCaptureChanged({});
5411 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005412
5413 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005414 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005415 mWindow->consumeCaptureEvent(false);
5416 mWindow->assertNoEvents();
5417}
5418
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005419TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5420 requestAndVerifyPointerCapture(mWindow, true);
5421
5422 // The first window loses focus.
5423 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005424 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005425 mWindow->consumeCaptureEvent(false);
5426
5427 // Request Pointer Capture from the second window before the notification from InputReader
5428 // arrives.
5429 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005430 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005431
5432 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005433 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005434
5435 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005436 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005437
5438 mSecondWindow->consumeFocusEvent(true);
5439 mSecondWindow->consumeCaptureEvent(true);
5440}
5441
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005442TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5443 // App repeatedly enables and disables capture.
5444 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5445 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5446 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5447 mFakePolicy->assertSetPointerCaptureCalled(false);
5448 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5449 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5450
5451 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5452 // first request is now stale, this should do nothing.
5453 notifyPointerCaptureChanged(firstRequest);
5454 mWindow->assertNoEvents();
5455
5456 // InputReader notifies that the second request was enabled.
5457 notifyPointerCaptureChanged(secondRequest);
5458 mWindow->consumeCaptureEvent(true);
5459}
5460
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005461class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5462protected:
5463 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005464
5465 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5466 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5467
5468 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5469 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5470
5471 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5472 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5473 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5474 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5475 MAXIMUM_OBSCURING_OPACITY);
5476
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005477 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005478 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005479 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005480
5481 sp<FakeWindowHandle> mTouchWindow;
5482
5483 virtual void SetUp() override {
5484 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005485 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005486 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5487 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5488 }
5489
5490 virtual void TearDown() override {
5491 InputDispatcherTest::TearDown();
5492 mTouchWindow.clear();
5493 }
5494
chaviw3277faf2021-05-19 16:45:23 -05005495 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5496 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005497 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005498 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005499 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005500 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005501 return window;
5502 }
5503
5504 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5505 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5506 sp<FakeWindowHandle> window =
5507 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5508 // Generate an arbitrary PID based on the UID
5509 window->setOwnerInfo(1777 + (uid % 10000), uid);
5510 return window;
5511 }
5512
5513 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5514 NotifyMotionArgs args =
5515 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5516 ADISPLAY_ID_DEFAULT, points);
5517 mDispatcher->notifyMotion(&args);
5518 }
5519};
5520
5521TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005522 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005523 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005524 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005525
5526 touch();
5527
5528 mTouchWindow->assertNoEvents();
5529}
5530
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005531TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005532 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5533 const sp<FakeWindowHandle>& w =
5534 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5535 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5536
5537 touch();
5538
5539 mTouchWindow->assertNoEvents();
5540}
5541
5542TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005543 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5544 const sp<FakeWindowHandle>& w =
5545 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5546 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5547
5548 touch();
5549
5550 w->assertNoEvents();
5551}
5552
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005553TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005554 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5555 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005556
5557 touch();
5558
5559 mTouchWindow->consumeAnyMotionDown();
5560}
5561
5562TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005563 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005564 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005565 w->setFrame(Rect(0, 0, 50, 50));
5566 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005567
5568 touch({PointF{100, 100}});
5569
5570 mTouchWindow->consumeAnyMotionDown();
5571}
5572
5573TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005574 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005575 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005576 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5577
5578 touch();
5579
5580 mTouchWindow->consumeAnyMotionDown();
5581}
5582
5583TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5584 const sp<FakeWindowHandle>& w =
5585 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5586 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005587
5588 touch();
5589
5590 mTouchWindow->consumeAnyMotionDown();
5591}
5592
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005593TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5594 const sp<FakeWindowHandle>& w =
5595 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5596 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5597
5598 touch();
5599
5600 w->assertNoEvents();
5601}
5602
5603/**
5604 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5605 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5606 * window, the occluding window will still receive ACTION_OUTSIDE event.
5607 */
5608TEST_F(InputDispatcherUntrustedTouchesTest,
5609 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5610 const sp<FakeWindowHandle>& w =
5611 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005612 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005613 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5614
5615 touch();
5616
5617 w->consumeMotionOutside();
5618}
5619
5620TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5621 const sp<FakeWindowHandle>& w =
5622 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005623 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005624 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5625
5626 touch();
5627
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005628 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005629}
5630
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005631TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005632 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005633 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5634 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005635 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5636
5637 touch();
5638
5639 mTouchWindow->consumeAnyMotionDown();
5640}
5641
5642TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5643 const sp<FakeWindowHandle>& w =
5644 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5645 MAXIMUM_OBSCURING_OPACITY);
5646 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005647
5648 touch();
5649
5650 mTouchWindow->consumeAnyMotionDown();
5651}
5652
5653TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005654 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005655 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5656 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005657 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5658
5659 touch();
5660
5661 mTouchWindow->assertNoEvents();
5662}
5663
5664TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5665 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5666 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005667 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5668 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005669 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005670 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5671 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005672 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5673
5674 touch();
5675
5676 mTouchWindow->assertNoEvents();
5677}
5678
5679TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5680 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5681 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005682 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5683 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005684 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005685 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5686 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005687 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5688
5689 touch();
5690
5691 mTouchWindow->consumeAnyMotionDown();
5692}
5693
5694TEST_F(InputDispatcherUntrustedTouchesTest,
5695 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5696 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005697 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5698 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005699 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005700 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5701 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005702 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5703
5704 touch();
5705
5706 mTouchWindow->consumeAnyMotionDown();
5707}
5708
5709TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5710 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005711 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5712 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005713 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005714 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5715 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005716 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005717
5718 touch();
5719
5720 mTouchWindow->assertNoEvents();
5721}
5722
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005723TEST_F(InputDispatcherUntrustedTouchesTest,
5724 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5725 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005726 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5727 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005728 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005729 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5730 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005731 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5732
5733 touch();
5734
5735 mTouchWindow->assertNoEvents();
5736}
5737
5738TEST_F(InputDispatcherUntrustedTouchesTest,
5739 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5740 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005741 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5742 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005743 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005744 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5745 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005746 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5747
5748 touch();
5749
5750 mTouchWindow->consumeAnyMotionDown();
5751}
5752
5753TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5754 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005755 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5756 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005757 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5758
5759 touch();
5760
5761 mTouchWindow->consumeAnyMotionDown();
5762}
5763
5764TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5765 const sp<FakeWindowHandle>& w =
5766 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5767 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5768
5769 touch();
5770
5771 mTouchWindow->consumeAnyMotionDown();
5772}
5773
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005774TEST_F(InputDispatcherUntrustedTouchesTest,
5775 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5776 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5777 const sp<FakeWindowHandle>& w =
5778 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5779 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5780
5781 touch();
5782
5783 mTouchWindow->assertNoEvents();
5784}
5785
5786TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5787 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5788 const sp<FakeWindowHandle>& w =
5789 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5790 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5791
5792 touch();
5793
5794 mTouchWindow->consumeAnyMotionDown();
5795}
5796
5797TEST_F(InputDispatcherUntrustedTouchesTest,
5798 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5799 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5800 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005801 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5802 OPACITY_ABOVE_THRESHOLD);
5803 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5804
5805 touch();
5806
5807 mTouchWindow->consumeAnyMotionDown();
5808}
5809
5810TEST_F(InputDispatcherUntrustedTouchesTest,
5811 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5812 const sp<FakeWindowHandle>& w1 =
5813 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5814 OPACITY_BELOW_THRESHOLD);
5815 const sp<FakeWindowHandle>& w2 =
5816 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5817 OPACITY_BELOW_THRESHOLD);
5818 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5819
5820 touch();
5821
5822 mTouchWindow->assertNoEvents();
5823}
5824
5825/**
5826 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5827 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5828 * (which alone would result in allowing touches) does not affect the blocking behavior.
5829 */
5830TEST_F(InputDispatcherUntrustedTouchesTest,
5831 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5832 const sp<FakeWindowHandle>& wB =
5833 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5834 OPACITY_BELOW_THRESHOLD);
5835 const sp<FakeWindowHandle>& wC =
5836 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5837 OPACITY_BELOW_THRESHOLD);
5838 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5839
5840 touch();
5841
5842 mTouchWindow->assertNoEvents();
5843}
5844
5845/**
5846 * This test is testing that a window from a different UID but with same application token doesn't
5847 * block the touch. Apps can share the application token for close UI collaboration for example.
5848 */
5849TEST_F(InputDispatcherUntrustedTouchesTest,
5850 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5851 const sp<FakeWindowHandle>& w =
5852 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5853 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005854 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5855
5856 touch();
5857
5858 mTouchWindow->consumeAnyMotionDown();
5859}
5860
arthurhungb89ccb02020-12-30 16:19:01 +08005861class InputDispatcherDragTests : public InputDispatcherTest {
5862protected:
5863 std::shared_ptr<FakeApplicationHandle> mApp;
5864 sp<FakeWindowHandle> mWindow;
5865 sp<FakeWindowHandle> mSecondWindow;
5866 sp<FakeWindowHandle> mDragWindow;
5867
5868 void SetUp() override {
5869 InputDispatcherTest::SetUp();
5870 mApp = std::make_shared<FakeApplicationHandle>();
5871 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5872 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005873 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005874
5875 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5876 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005877 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005878
5879 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5880 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5881 }
5882
5883 // Start performing drag, we will create a drag window and transfer touch to it.
5884 void performDrag() {
5885 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5886 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5887 {50, 50}))
5888 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5889
5890 // Window should receive motion event.
5891 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5892
5893 // The drag window covers the entire display
5894 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5895 mDispatcher->setInputWindows(
5896 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5897
5898 // Transfer touch focus to the drag window
5899 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5900 true /* isDragDrop */);
5901 mWindow->consumeMotionCancel();
5902 mDragWindow->consumeMotionDown();
5903 }
arthurhung6d4bed92021-03-17 11:59:33 +08005904
5905 // Start performing drag, we will create a drag window and transfer touch to it.
5906 void performStylusDrag() {
5907 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5908 injectMotionEvent(mDispatcher,
5909 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5910 AINPUT_SOURCE_STYLUS)
5911 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5912 .pointer(PointerBuilder(0,
5913 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5914 .x(50)
5915 .y(50))
5916 .build()));
5917 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5918
5919 // The drag window covers the entire display
5920 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5921 mDispatcher->setInputWindows(
5922 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5923
5924 // Transfer touch focus to the drag window
5925 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5926 true /* isDragDrop */);
5927 mWindow->consumeMotionCancel();
5928 mDragWindow->consumeMotionDown();
5929 }
arthurhungb89ccb02020-12-30 16:19:01 +08005930};
5931
5932TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5933 performDrag();
5934
5935 // Move on window.
5936 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5937 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5938 ADISPLAY_ID_DEFAULT, {50, 50}))
5939 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5940 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5941 mWindow->consumeDragEvent(false, 50, 50);
5942 mSecondWindow->assertNoEvents();
5943
5944 // Move to another window.
5945 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5946 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5947 ADISPLAY_ID_DEFAULT, {150, 50}))
5948 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5949 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5950 mWindow->consumeDragEvent(true, 150, 50);
5951 mSecondWindow->consumeDragEvent(false, 50, 50);
5952
5953 // Move back to original window.
5954 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5955 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5956 ADISPLAY_ID_DEFAULT, {50, 50}))
5957 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5958 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5959 mWindow->consumeDragEvent(false, 50, 50);
5960 mSecondWindow->consumeDragEvent(true, -50, 50);
5961
5962 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5963 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5964 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5965 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5966 mWindow->assertNoEvents();
5967 mSecondWindow->assertNoEvents();
5968}
5969
arthurhungf452d0b2021-01-06 00:19:52 +08005970TEST_F(InputDispatcherDragTests, DragAndDrop) {
5971 performDrag();
5972
5973 // Move on window.
5974 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5975 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5976 ADISPLAY_ID_DEFAULT, {50, 50}))
5977 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5978 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5979 mWindow->consumeDragEvent(false, 50, 50);
5980 mSecondWindow->assertNoEvents();
5981
5982 // Move to another window.
5983 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5984 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5985 ADISPLAY_ID_DEFAULT, {150, 50}))
5986 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5987 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5988 mWindow->consumeDragEvent(true, 150, 50);
5989 mSecondWindow->consumeDragEvent(false, 50, 50);
5990
5991 // drop to another window.
5992 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5993 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5994 {150, 50}))
5995 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5996 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5997 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5998 mWindow->assertNoEvents();
5999 mSecondWindow->assertNoEvents();
6000}
6001
arthurhung6d4bed92021-03-17 11:59:33 +08006002TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6003 performStylusDrag();
6004
6005 // Move on window and keep button pressed.
6006 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6007 injectMotionEvent(mDispatcher,
6008 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6009 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6010 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6011 .x(50)
6012 .y(50))
6013 .build()))
6014 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6015 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6016 mWindow->consumeDragEvent(false, 50, 50);
6017 mSecondWindow->assertNoEvents();
6018
6019 // Move to another window and release button, expect to drop item.
6020 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6021 injectMotionEvent(mDispatcher,
6022 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6023 .buttonState(0)
6024 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6025 .x(150)
6026 .y(50))
6027 .build()))
6028 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6029 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6030 mWindow->assertNoEvents();
6031 mSecondWindow->assertNoEvents();
6032 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6033
6034 // nothing to the window.
6035 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6036 injectMotionEvent(mDispatcher,
6037 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6038 .buttonState(0)
6039 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6040 .x(150)
6041 .y(50))
6042 .build()))
6043 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6044 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6045 mWindow->assertNoEvents();
6046 mSecondWindow->assertNoEvents();
6047}
6048
Arthur Hung6d0571e2021-04-09 20:18:16 +08006049TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6050 performDrag();
6051
6052 // Set second window invisible.
6053 mSecondWindow->setVisible(false);
6054 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6055
6056 // Move on window.
6057 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6058 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6059 ADISPLAY_ID_DEFAULT, {50, 50}))
6060 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6061 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6062 mWindow->consumeDragEvent(false, 50, 50);
6063 mSecondWindow->assertNoEvents();
6064
6065 // Move to another window.
6066 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6067 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6068 ADISPLAY_ID_DEFAULT, {150, 50}))
6069 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6070 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6071 mWindow->consumeDragEvent(true, 150, 50);
6072 mSecondWindow->assertNoEvents();
6073
6074 // drop to another window.
6075 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6076 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6077 {150, 50}))
6078 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6079 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6080 mFakePolicy->assertDropTargetEquals(nullptr);
6081 mWindow->assertNoEvents();
6082 mSecondWindow->assertNoEvents();
6083}
6084
Vishnu Nair062a8672021-09-03 16:07:44 -07006085class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6086
6087TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6088 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6089 sp<FakeWindowHandle> window =
6090 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6091 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
6092 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6093 window->setFocusable(true);
6094 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6095 setFocusedWindow(window);
6096 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6097
6098 // With the flag set, window should not get any input
6099 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6100 mDispatcher->notifyKey(&keyArgs);
6101 window->assertNoEvents();
6102
6103 NotifyMotionArgs motionArgs =
6104 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6105 ADISPLAY_ID_DEFAULT);
6106 mDispatcher->notifyMotion(&motionArgs);
6107 window->assertNoEvents();
6108
6109 // With the flag cleared, the window should get input
6110 window->setInputFeatures({});
6111 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6112
6113 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6114 mDispatcher->notifyKey(&keyArgs);
6115 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6116
6117 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6118 ADISPLAY_ID_DEFAULT);
6119 mDispatcher->notifyMotion(&motionArgs);
6120 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6121 window->assertNoEvents();
6122}
6123
6124TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6125 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6126 std::make_shared<FakeApplicationHandle>();
6127 sp<FakeWindowHandle> obscuringWindow =
6128 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6129 ADISPLAY_ID_DEFAULT);
6130 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6131 obscuringWindow->setOwnerInfo(111, 111);
6132 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6133 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6134 sp<FakeWindowHandle> window =
6135 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6136 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6137 window->setOwnerInfo(222, 222);
6138 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6139 window->setFocusable(true);
6140 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6141 setFocusedWindow(window);
6142 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6143
6144 // With the flag set, window should not get any input
6145 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6146 mDispatcher->notifyKey(&keyArgs);
6147 window->assertNoEvents();
6148
6149 NotifyMotionArgs motionArgs =
6150 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6151 ADISPLAY_ID_DEFAULT);
6152 mDispatcher->notifyMotion(&motionArgs);
6153 window->assertNoEvents();
6154
6155 // With the flag cleared, the window should get input
6156 window->setInputFeatures({});
6157 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6158
6159 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6160 mDispatcher->notifyKey(&keyArgs);
6161 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6162
6163 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6164 ADISPLAY_ID_DEFAULT);
6165 mDispatcher->notifyMotion(&motionArgs);
6166 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6167 window->assertNoEvents();
6168}
6169
6170TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6171 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6172 std::make_shared<FakeApplicationHandle>();
6173 sp<FakeWindowHandle> obscuringWindow =
6174 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6175 ADISPLAY_ID_DEFAULT);
6176 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6177 obscuringWindow->setOwnerInfo(111, 111);
6178 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6179 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6180 sp<FakeWindowHandle> window =
6181 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6182 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6183 window->setOwnerInfo(222, 222);
6184 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6185 window->setFocusable(true);
6186 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6187 setFocusedWindow(window);
6188 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6189
6190 // With the flag set, window should not get any input
6191 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6192 mDispatcher->notifyKey(&keyArgs);
6193 window->assertNoEvents();
6194
6195 NotifyMotionArgs motionArgs =
6196 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6197 ADISPLAY_ID_DEFAULT);
6198 mDispatcher->notifyMotion(&motionArgs);
6199 window->assertNoEvents();
6200
6201 // When the window is no longer obscured because it went on top, it should get input
6202 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6203
6204 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6205 mDispatcher->notifyKey(&keyArgs);
6206 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6207
6208 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6209 ADISPLAY_ID_DEFAULT);
6210 mDispatcher->notifyMotion(&motionArgs);
6211 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6212 window->assertNoEvents();
6213}
6214
Antonio Kantekf16f2832021-09-28 04:39:20 +00006215class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6216protected:
6217 std::shared_ptr<FakeApplicationHandle> mApp;
6218 sp<FakeWindowHandle> mWindow;
6219 sp<FakeWindowHandle> mSecondWindow;
6220
6221 void SetUp() override {
6222 InputDispatcherTest::SetUp();
6223
6224 mApp = std::make_shared<FakeApplicationHandle>();
6225 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6226 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006227 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006228 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6229 mSecondWindow->setFocusable(true);
6230
6231 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6232 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006233 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006234
6235 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
6236 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, INJECTOR_PID,
6237 INJECTOR_UID, /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006238 }
6239
Antonio Kantekea47acb2021-12-23 12:41:25 -08006240 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006241 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006242 mWindow->consumeTouchModeEvent(inTouchMode);
6243 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6244 }
6245};
6246
Antonio Kantek26defcf2022-02-08 01:12:27 +00006247TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006248 const WindowInfo& windowInfo = *mWindow->getInfo();
6249 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6250 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006251}
6252
Antonio Kantek26defcf2022-02-08 01:12:27 +00006253TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6254 const WindowInfo& windowInfo = *mWindow->getInfo();
6255 int32_t ownerPid = windowInfo.ownerPid;
6256 int32_t ownerUid = windowInfo.ownerUid;
6257 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6258 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6259 ownerUid, /* hasPermission */ false));
6260 mWindow->assertNoEvents();
6261 mSecondWindow->assertNoEvents();
6262}
6263
6264TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6265 const WindowInfo& windowInfo = *mWindow->getInfo();
6266 int32_t ownerPid = windowInfo.ownerPid;
6267 int32_t ownerUid = windowInfo.ownerUid;
6268 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6269 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6270 /* hasPermission */ true);
6271}
6272
Antonio Kantekf16f2832021-09-28 04:39:20 +00006273TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006274 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006275 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6276 windowInfo.ownerPid, windowInfo.ownerUid,
6277 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006278 mWindow->assertNoEvents();
6279 mSecondWindow->assertNoEvents();
6280}
6281
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006282class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6283public:
6284 sp<FakeWindowHandle> createSpy(const Flags<WindowInfo::Flag> flags) {
6285 std::shared_ptr<FakeApplicationHandle> application =
6286 std::make_shared<FakeApplicationHandle>();
6287 std::string name = "Fake Spy ";
6288 name += std::to_string(mSpyCount++);
6289 sp<FakeWindowHandle> spy =
6290 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
6291 spy->setInputFeatures(WindowInfo::Feature::SPY);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006292 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006293 spy->addFlags(flags);
6294 return spy;
6295 }
6296
6297 sp<FakeWindowHandle> createForeground() {
6298 std::shared_ptr<FakeApplicationHandle> application =
6299 std::make_shared<FakeApplicationHandle>();
6300 sp<FakeWindowHandle> window =
6301 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
6302 window->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006303 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006304 return window;
6305 }
6306
6307private:
6308 int mSpyCount{0};
6309};
6310
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006311using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006312/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006313 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6314 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006315TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6316 ScopedSilentDeath _silentDeath;
6317
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006318 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6319 spy->setTrustedOverlay(false);
6320 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6321 ".* not a trusted overlay");
6322}
6323
6324/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006325 * Input injection into a display with a spy window but no foreground windows should succeed.
6326 */
6327TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
6328 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6329 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6330
6331 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6332 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6333 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6334 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6335}
6336
6337/**
6338 * Verify the order in which different input windows receive events. The touched foreground window
6339 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6340 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6341 * receive events before ones belows it.
6342 *
6343 * Here, we set up a scenario with four windows in the following Z order from the top:
6344 * spy1, spy2, window, spy3.
6345 * We then inject an event and verify that the foreground "window" receives it first, followed by
6346 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6347 * window.
6348 */
6349TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6350 auto window = createForeground();
6351 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6352 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6353 auto spy3 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6354 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6355 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6356 const size_t numChannels = channels.size();
6357
6358 base::unique_fd epollFd(epoll_create1(0 /*flags*/));
6359 if (!epollFd.ok()) {
6360 FAIL() << "Failed to create epoll fd";
6361 }
6362
6363 for (size_t i = 0; i < numChannels; i++) {
6364 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6365 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6366 FAIL() << "Failed to add fd to epoll";
6367 }
6368 }
6369
6370 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6371 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6372 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6373
6374 std::vector<size_t> eventOrder;
6375 std::vector<struct epoll_event> events(numChannels);
6376 for (;;) {
6377 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6378 (100ms).count());
6379 if (nFds < 0) {
6380 FAIL() << "Failed to call epoll_wait";
6381 }
6382 if (nFds == 0) {
6383 break; // epoll_wait timed out
6384 }
6385 for (int i = 0; i < nFds; i++) {
6386 ASSERT_EQ(EPOLLIN, events[i].events);
6387 eventOrder.push_back(events[i].data.u64);
6388 channels[i]->consumeMotionDown();
6389 }
6390 }
6391
6392 // Verify the order in which the events were received.
6393 EXPECT_EQ(3u, eventOrder.size());
6394 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6395 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6396 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6397}
6398
6399/**
6400 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6401 */
6402TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6403 auto window = createForeground();
6404 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCHABLE);
6405 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6406
6407 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6408 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6409 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6410 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6411 spy->assertNoEvents();
6412}
6413
6414/**
6415 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6416 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6417 * to the window.
6418 */
6419TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6420 auto window = createForeground();
6421 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6422 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6423 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6424
6425 // Inject an event outside the spy window's touchable region.
6426 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6427 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6428 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6429 window->consumeMotionDown();
6430 spy->assertNoEvents();
6431 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6432 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6433 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6434 window->consumeMotionUp();
6435 spy->assertNoEvents();
6436
6437 // Inject an event inside the spy window's touchable region.
6438 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6439 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6440 {5, 10}))
6441 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6442 window->consumeMotionDown();
6443 spy->consumeMotionDown();
6444}
6445
6446/**
6447 * A spy window that is a modal window will receive gestures outside of its frame and touchable
6448 * region.
6449 */
6450TEST_F(InputDispatcherSpyWindowTest, ModalWindow) {
6451 auto window = createForeground();
6452 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6453 // This spy window does not have the NOT_TOUCH_MODAL flag set.
6454 spy->setFrame(Rect{0, 0, 20, 20});
6455 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6456
6457 // Inject an event outside the spy window's frame and touchable region.
6458 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6459 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6460 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6461 window->consumeMotionDown();
6462 spy->consumeMotionDown();
6463}
6464
6465/**
6466 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006467 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006468 */
6469TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6470 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006471 window->setOwnerInfo(12, 34);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006472 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006473 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006474 spy->setFrame(Rect{0, 0, 20, 20});
6475 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6476
6477 // Inject an event outside the spy window's frame and touchable region.
6478 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006479 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6480 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006481 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6482 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006483 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006484}
6485
6486/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006487 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6488 * any other windows - including other spy windows - will also be cancelled.
6489 */
6490TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6491 auto window = createForeground();
6492 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6493 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6494 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6495
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 spy1->consumeMotionDown();
6501 spy2->consumeMotionDown();
6502
6503 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006504 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006505 spy2->assertNoEvents();
6506 spy1->consumeMotionCancel();
6507 window->consumeMotionCancel();
6508
6509 // The rest of the gesture should only be sent to the second spy window.
6510 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6511 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6512 ADISPLAY_ID_DEFAULT))
6513 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6514 spy2->consumeMotionMove();
6515 spy1->assertNoEvents();
6516 window->assertNoEvents();
6517}
6518
6519/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006520 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
6521 * in the middle of the gesture.
6522 */
6523TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
6524 auto window = createForeground();
6525 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6526 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6527
6528 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6529 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6530 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6531 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6532 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6533
6534 window->releaseChannel();
6535
6536 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6537
6538 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6539 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6540 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6541 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6542}
6543
6544/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006545 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
6546 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006547 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006548TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
6549 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006550 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006551 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
6552
6553 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6554
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006555 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006556 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6557 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6558 {100, 200}))
6559 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006560 spy->consumeMotionDown();
6561 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006562
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006563 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006564 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006565 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006566
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006567 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006568 const MotionEvent secondFingerDownEvent =
6569 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6570 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6571 AINPUT_SOURCE_TOUCHSCREEN)
6572 .displayId(ADISPLAY_ID_DEFAULT)
6573 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6574 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6575 .x(100)
6576 .y(200))
6577 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6578 .build();
6579 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6580 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6581 InputEventInjectionSync::WAIT_FOR_RESULT))
6582 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6583
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006584 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6585
6586 // Third finger goes down outside all windows, so injection should fail.
6587 const MotionEvent thirdFingerDownEvent =
6588 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6589 (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6590 AINPUT_SOURCE_TOUCHSCREEN)
6591 .displayId(ADISPLAY_ID_DEFAULT)
6592 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6593 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6594 .x(100)
6595 .y(200))
6596 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6597 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
6598 .build();
6599 ASSERT_EQ(InputEventInjectionResult::FAILED,
6600 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
6601 InputEventInjectionSync::WAIT_FOR_RESULT))
6602 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6603
6604 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006605 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006606}
6607
6608/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006609 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6610 * pointers that are down within its bounds.
6611 */
6612TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6613 auto windowLeft = createForeground();
6614 windowLeft->setFrame({0, 0, 100, 200});
6615 auto windowRight = createForeground();
6616 windowRight->setFrame({100, 0, 200, 200});
6617 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6618 spy->setFrame({0, 0, 200, 200});
6619 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6620
6621 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6622 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6623 {50, 50}))
6624 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6625 windowLeft->consumeMotionDown();
6626 spy->consumeMotionDown();
6627
6628 const MotionEvent secondFingerDownEvent =
6629 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6630 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6631 AINPUT_SOURCE_TOUCHSCREEN)
6632 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6633 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6634 .pointer(
6635 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6636 .build();
6637 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6638 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6639 InputEventInjectionSync::WAIT_FOR_RESULT))
6640 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6641 windowRight->consumeMotionDown();
6642 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6643}
6644
6645/**
6646 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6647 * the spy should receive the second pointer with ACTION_DOWN.
6648 */
6649TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6650 auto window = createForeground();
6651 window->setFrame({0, 0, 200, 200});
6652 auto spyRight = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6653 spyRight->setFrame({100, 0, 200, 200});
6654 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6655
6656 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6657 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6658 {50, 50}))
6659 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6660 window->consumeMotionDown();
6661 spyRight->assertNoEvents();
6662
6663 const MotionEvent secondFingerDownEvent =
6664 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6665 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6666 AINPUT_SOURCE_TOUCHSCREEN)
6667 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6668 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6669 .pointer(
6670 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6671 .build();
6672 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6673 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6674 InputEventInjectionSync::WAIT_FOR_RESULT))
6675 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6676 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6677 spyRight->consumeMotionDown();
6678}
6679
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006680/**
6681 * The spy window should not be able to affect whether or not touches are split. Only the foreground
6682 * windows should be allowed to control split touch.
6683 */
6684TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
6685 // Create a touch modal spy that spies on the entire display.
6686 // This spy window does not set the SPLIT_TOUCH flag. However, we still expect to split touches
6687 // because a foreground window has not disabled splitting.
6688 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6689
6690 // Create a non touch modal window that supports split touch.
6691 auto window = createForeground();
6692 window->setFrame(Rect(0, 0, 100, 100));
6693 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
6694
6695 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6696
6697 // First finger down, no window touched.
6698 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6699 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6700 {100, 200}))
6701 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6702 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6703 window->assertNoEvents();
6704
6705 // Second finger down on window, the window should receive touch down.
6706 const MotionEvent secondFingerDownEvent =
6707 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6708 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6709 AINPUT_SOURCE_TOUCHSCREEN)
6710 .displayId(ADISPLAY_ID_DEFAULT)
6711 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6712 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6713 .x(100)
6714 .y(200))
6715 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6716 .build();
6717 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6718 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6719 InputEventInjectionSync::WAIT_FOR_RESULT))
6720 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6721
6722 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6723 spy->consumeMotionPointerDown(1 /* pointerIndex */);
6724}
6725
6726/**
6727 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
6728 * do not receive key events.
6729 */
6730TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
6731 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6732 spy->setFocusable(false);
6733
6734 auto window = createForeground();
6735 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6736 setFocusedWindow(window);
6737 window->consumeFocusEvent(true);
6738
6739 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6740 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6741 window->consumeKeyDown(ADISPLAY_ID_NONE);
6742
6743 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6744 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6745 window->consumeKeyUp(ADISPLAY_ID_NONE);
6746
6747 spy->assertNoEvents();
6748}
6749
Prabir Pradhand65552b2021-10-07 11:23:50 -07006750class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6751public:
6752 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6753 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6754 std::make_shared<FakeApplicationHandle>();
6755 sp<FakeWindowHandle> overlay =
6756 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6757 ADISPLAY_ID_DEFAULT);
6758 overlay->setFocusable(false);
6759 overlay->setOwnerInfo(111, 111);
6760 overlay->setFlags(WindowInfo::Flag::NOT_TOUCHABLE | WindowInfo::Flag::SPLIT_TOUCH);
6761 overlay->setInputFeatures(WindowInfo::Feature::INTERCEPTS_STYLUS);
6762 overlay->setTrustedOverlay(true);
6763
6764 std::shared_ptr<FakeApplicationHandle> application =
6765 std::make_shared<FakeApplicationHandle>();
6766 sp<FakeWindowHandle> window =
6767 new FakeWindowHandle(application, mDispatcher, "Application window",
6768 ADISPLAY_ID_DEFAULT);
6769 window->setFocusable(true);
6770 window->setOwnerInfo(222, 222);
6771 window->setFlags(WindowInfo::Flag::SPLIT_TOUCH);
6772
6773 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6774 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6775 setFocusedWindow(window);
6776 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6777 return {std::move(overlay), std::move(window)};
6778 }
6779
6780 void sendFingerEvent(int32_t action) {
6781 NotifyMotionArgs motionArgs =
6782 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6783 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6784 mDispatcher->notifyMotion(&motionArgs);
6785 }
6786
6787 void sendStylusEvent(int32_t action) {
6788 NotifyMotionArgs motionArgs =
6789 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6790 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6791 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6792 mDispatcher->notifyMotion(&motionArgs);
6793 }
6794};
6795
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006796using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
6797
6798TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
6799 ScopedSilentDeath _silentDeath;
6800
Prabir Pradhand65552b2021-10-07 11:23:50 -07006801 auto [overlay, window] = setupStylusOverlayScenario();
6802 overlay->setTrustedOverlay(false);
6803 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6804 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6805 ".* not a trusted overlay");
6806}
6807
6808TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6809 auto [overlay, window] = setupStylusOverlayScenario();
6810 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6811
6812 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6813 overlay->consumeMotionDown();
6814 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6815 overlay->consumeMotionUp();
6816
6817 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6818 window->consumeMotionDown();
6819 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6820 window->consumeMotionUp();
6821
6822 overlay->assertNoEvents();
6823 window->assertNoEvents();
6824}
6825
6826TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6827 auto [overlay, window] = setupStylusOverlayScenario();
6828 overlay->setInputFeatures(overlay->getInfo()->inputFeatures | WindowInfo::Feature::SPY);
6829 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6830
6831 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6832 overlay->consumeMotionDown();
6833 window->consumeMotionDown();
6834 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6835 overlay->consumeMotionUp();
6836 window->consumeMotionUp();
6837
6838 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6839 window->consumeMotionDown();
6840 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6841 window->consumeMotionUp();
6842
6843 overlay->assertNoEvents();
6844 window->assertNoEvents();
6845}
6846
Garfield Tane84e6f92019-08-29 17:28:41 -07006847} // namespace android::inputdispatcher