blob: da65e176e526f2e3c86375ca7cda209a7018fabc [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 Wright8e9a8562022-02-09 13:44:29 +000024#include <fcntl.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080025#include <gtest/gtest.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100026#include <input/Input.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080027#include <linux/input.h>
Prabir Pradhan07e05b62021-11-19 03:57:24 -080028#include <sys/epoll.h>
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100029
Garfield Tan1c7bc862020-01-28 13:24:04 -080030#include <cinttypes>
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -070031#include <thread>
Garfield Tan1c7bc862020-01-28 13:24:04 -080032#include <unordered_set>
chaviwd1c23182019-12-20 18:44:56 -080033#include <vector>
Michael Wrightd02c5b62014-02-10 15:10:22 -080034
Garfield Tan1c7bc862020-01-28 13:24:04 -080035using android::base::StringPrintf;
chaviw3277faf2021-05-19 16:45:23 -050036using android::gui::FocusRequest;
37using android::gui::TouchOcclusionMode;
38using android::gui::WindowInfo;
39using android::gui::WindowInfoHandle;
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -080040using android::os::InputEventInjectionResult;
41using android::os::InputEventInjectionSync;
Michael Wright44753b12020-07-08 13:48:11 +010042using namespace android::flag_operators;
Garfield Tan1c7bc862020-01-28 13:24:04 -080043
Garfield Tane84e6f92019-08-29 17:28:41 -070044namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080045
46// An arbitrary time value.
47static const nsecs_t ARBITRARY_TIME = 1234;
48
49// An arbitrary device id.
50static const int32_t DEVICE_ID = 1;
51
Jeff Brownf086ddb2014-02-11 14:28:48 -080052// An arbitrary display id.
Arthur Hungabbb9d82021-09-01 14:52:30 +000053static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
54static constexpr int32_t SECOND_DISPLAY_ID = 1;
Jeff Brownf086ddb2014-02-11 14:28:48 -080055
Michael Wrightd02c5b62014-02-10 15:10:22 -080056// An arbitrary injector pid / uid pair that has permission to inject events.
57static const int32_t INJECTOR_PID = 999;
58static const int32_t INJECTOR_UID = 1001;
59
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000060// An arbitrary pid of the gesture monitor window
61static constexpr int32_t MONITOR_PID = 2001;
62
chaviwd1c23182019-12-20 18:44:56 -080063struct PointF {
64 float x;
65 float y;
66};
Michael Wrightd02c5b62014-02-10 15:10:22 -080067
Gang Wang342c9272020-01-13 13:15:04 -050068/**
69 * Return a DOWN key event with KEYCODE_A.
70 */
71static KeyEvent getTestKeyEvent() {
72 KeyEvent event;
73
Garfield Tanfbe732e2020-01-24 11:26:14 -080074 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
75 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
76 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050077 return event;
78}
79
Siarhei Vishniakouca205502021-07-16 21:31:58 +000080static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
81 ASSERT_EQ(expectedAction, receivedAction)
82 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
83 << MotionEvent::actionToString(receivedAction);
84}
85
Michael Wrightd02c5b62014-02-10 15:10:22 -080086// --- FakeInputDispatcherPolicy ---
87
88class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
89 InputDispatcherConfiguration mConfig;
90
91protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100092 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -080093
94public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -100095 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +080096
Siarhei Vishniakou8935a802019-11-15 16:41:44 -080097 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -070098 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
99 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
100 EXPECT_EQ(event.getDisplayId(), args.displayId);
101
102 const auto& keyEvent = static_cast<const KeyEvent&>(event);
103 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
104 EXPECT_EQ(keyEvent.getAction(), args.action);
105 });
Jackal Guof9696682018-10-05 12:23:23 +0800106 }
107
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700108 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
109 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
110 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
111 EXPECT_EQ(event.getDisplayId(), args.displayId);
112
113 const auto& motionEvent = static_cast<const MotionEvent&>(event);
114 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
115 EXPECT_EQ(motionEvent.getAction(), args.action);
116 EXPECT_EQ(motionEvent.getX(0), point.x);
117 EXPECT_EQ(motionEvent.getY(0), point.y);
118 EXPECT_EQ(motionEvent.getRawX(0), point.x);
119 EXPECT_EQ(motionEvent.getRawY(0), point.y);
120 });
Jackal Guof9696682018-10-05 12:23:23 +0800121 }
122
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700123 void assertFilterInputEventWasNotCalled() {
124 std::scoped_lock lock(mLock);
125 ASSERT_EQ(nullptr, mFilteredEvent);
126 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800127
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800128 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700129 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800130 ASSERT_TRUE(mConfigurationChangedTime)
131 << "Timed out waiting for configuration changed call";
132 ASSERT_EQ(*mConfigurationChangedTime, when);
133 mConfigurationChangedTime = std::nullopt;
134 }
135
136 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700137 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800138 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800139 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800140 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
141 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
142 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
143 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
144 mLastNotifySwitch = std::nullopt;
145 }
146
chaviwfd6d3512019-03-25 13:23:49 -0700147 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700148 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800149 ASSERT_EQ(touchedToken, mOnPointerDownToken);
150 mOnPointerDownToken.clear();
151 }
152
153 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700154 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800155 ASSERT_TRUE(mOnPointerDownToken == nullptr)
156 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700157 }
158
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700159 // This function must be called soon after the expected ANR timer starts,
160 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500161 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700162 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500163 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
164 std::shared_ptr<InputApplicationHandle> application;
165 { // acquire lock
166 std::unique_lock lock(mLock);
167 android::base::ScopedLockAssertion assumeLocked(mLock);
168 ASSERT_NO_FATAL_FAILURE(
169 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
170 } // release lock
171 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700172 }
173
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000174 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
175 const sp<IBinder>& expectedConnectionToken) {
176 sp<IBinder> connectionToken = getUnresponsiveWindowToken(timeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500177 ASSERT_EQ(expectedConnectionToken, connectionToken);
178 }
179
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000180 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedConnectionToken) {
181 sp<IBinder> connectionToken = getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500182 ASSERT_EQ(expectedConnectionToken, connectionToken);
183 }
184
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000185 void assertNotifyMonitorUnresponsiveWasCalled(std::chrono::nanoseconds timeout) {
186 int32_t pid = getUnresponsiveMonitorPid(timeout);
187 ASSERT_EQ(MONITOR_PID, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500188 }
189
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000190 void assertNotifyMonitorResponsiveWasCalled() {
191 int32_t pid = getResponsiveMonitorPid();
192 ASSERT_EQ(MONITOR_PID, pid);
193 }
194
195 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500196 std::unique_lock lock(mLock);
197 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000198 return getAnrTokenLockedInterruptible(timeout, mAnrWindowTokens, lock);
199 }
200
201 sp<IBinder> getResponsiveWindowToken() {
202 std::unique_lock lock(mLock);
203 android::base::ScopedLockAssertion assumeLocked(mLock);
204 return getAnrTokenLockedInterruptible(0s, mResponsiveWindowTokens, lock);
205 }
206
207 int32_t getUnresponsiveMonitorPid(std::chrono::nanoseconds timeout) {
208 std::unique_lock lock(mLock);
209 android::base::ScopedLockAssertion assumeLocked(mLock);
210 return getAnrTokenLockedInterruptible(timeout, mAnrMonitorPids, lock);
211 }
212
213 int32_t getResponsiveMonitorPid() {
214 std::unique_lock lock(mLock);
215 android::base::ScopedLockAssertion assumeLocked(mLock);
216 return getAnrTokenLockedInterruptible(0s, mResponsiveMonitorPids, lock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500217 }
218
219 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
220 // for a specific container to become non-empty. When the container is non-empty, return the
221 // first entry from the container and erase it.
222 template <class T>
223 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
224 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700225 // If there is an ANR, Dispatcher won't be idle because there are still events
226 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
227 // before checking if ANR was called.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500228 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
229 // to provide it some time to act. 100ms seems reasonable.
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800230 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
231 const std::chrono::time_point start = std::chrono::steady_clock::now();
232 std::optional<T> token =
233 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
234 if (!token.has_value()) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500235 ADD_FAILURE() << "Did not receive the ANR callback";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000236 return {};
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700237 }
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800238
239 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700240 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
241 // the dispatcher started counting before this function was called
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700242 if (std::chrono::abs(timeout - waited) > 100ms) {
243 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
244 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
245 << "ms, but waited "
246 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
247 << "ms instead";
248 }
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800249 return *token;
250 }
251
252 template <class T>
253 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
254 std::queue<T>& storage,
255 std::unique_lock<std::mutex>& lock,
256 std::condition_variable& condition)
257 REQUIRES(mLock) {
258 condition.wait_for(lock, timeout,
259 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
260 if (storage.empty()) {
261 ADD_FAILURE() << "Did not receive the expected callback";
262 return std::nullopt;
263 }
264 T item = storage.front();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500265 storage.pop();
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800266 return std::make_optional(item);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700267 }
268
269 void assertNotifyAnrWasNotCalled() {
270 std::scoped_lock lock(mLock);
271 ASSERT_TRUE(mAnrApplications.empty());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000272 ASSERT_TRUE(mAnrWindowTokens.empty());
273 ASSERT_TRUE(mAnrMonitorPids.empty());
274 ASSERT_TRUE(mResponsiveWindowTokens.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500275 << "ANR was not called, but please also consume the 'connection is responsive' "
276 "signal";
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000277 ASSERT_TRUE(mResponsiveMonitorPids.empty())
278 << "Monitor ANR was not called, but please also consume the 'monitor is responsive'"
279 " signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700280 }
281
Garfield Tan1c7bc862020-01-28 13:24:04 -0800282 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
283 mConfig.keyRepeatTimeout = timeout;
284 mConfig.keyRepeatDelay = delay;
285 }
286
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000287 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800288 std::unique_lock lock(mLock);
289 base::ScopedLockAssertion assumeLocked(mLock);
290
291 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
292 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000293 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800294 enabled;
295 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000296 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
297 << ") to be called.";
298 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800299 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000300 auto request = *mPointerCaptureRequest;
301 mPointerCaptureRequest.reset();
302 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800303 }
304
305 void assertSetPointerCaptureNotCalled() {
306 std::unique_lock lock(mLock);
307 base::ScopedLockAssertion assumeLocked(mLock);
308
309 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000310 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800311 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000312 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800313 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000314 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800315 }
316
arthurhungf452d0b2021-01-06 00:19:52 +0800317 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
318 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800319 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800320 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800321 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800322 }
323
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800324 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
325 std::unique_lock lock(mLock);
326 base::ScopedLockAssertion assumeLocked(mLock);
327 std::optional<sp<IBinder>> receivedToken =
328 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
329 mNotifyInputChannelBroken);
330 ASSERT_TRUE(receivedToken.has_value());
331 ASSERT_EQ(token, *receivedToken);
332 }
333
Michael Wrightd02c5b62014-02-10 15:10:22 -0800334private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700335 std::mutex mLock;
336 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
337 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
338 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
339 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800340
Prabir Pradhan99987712020-11-10 18:43:05 -0800341 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000342
343 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800344
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700345 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700346 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000347 std::queue<sp<IBinder>> mAnrWindowTokens GUARDED_BY(mLock);
348 std::queue<sp<IBinder>> mResponsiveWindowTokens GUARDED_BY(mLock);
349 std::queue<int32_t> mAnrMonitorPids GUARDED_BY(mLock);
350 std::queue<int32_t> mResponsiveMonitorPids GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700351 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800352 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
353 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700354
arthurhungf452d0b2021-01-06 00:19:52 +0800355 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800356 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800357
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600358 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700359 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800360 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800361 }
362
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000363 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700364 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000365 mAnrWindowTokens.push(connectionToken);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700366 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500367 }
368
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000369 void notifyMonitorUnresponsive(int32_t pid, const std::string&) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500370 std::scoped_lock lock(mLock);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000371 mAnrMonitorPids.push(pid);
372 mNotifyAnr.notify_all();
373 }
374
375 void notifyWindowResponsive(const sp<IBinder>& connectionToken) override {
376 std::scoped_lock lock(mLock);
377 mResponsiveWindowTokens.push(connectionToken);
378 mNotifyAnr.notify_all();
379 }
380
381 void notifyMonitorResponsive(int32_t pid) override {
382 std::scoped_lock lock(mLock);
383 mResponsiveMonitorPids.push(pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500384 mNotifyAnr.notify_all();
385 }
386
387 void notifyNoFocusedWindowAnr(
388 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
389 std::scoped_lock lock(mLock);
390 mAnrApplications.push(applicationHandle);
391 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800392 }
393
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800394 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
395 std::scoped_lock lock(mLock);
396 mBrokenInputChannels.push(connectionToken);
397 mNotifyInputChannelBroken.notify_all();
398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800399
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600400 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700401
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600402 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700403 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
404 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
405 const std::vector<float>& values) override {}
406
407 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
408 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000409
Chris Yefb552902021-02-03 17:18:37 -0800410 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
411
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600412 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413 *outConfig = mConfig;
414 }
415
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600416 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700417 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800418 switch (inputEvent->getType()) {
419 case AINPUT_EVENT_TYPE_KEY: {
420 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800421 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800422 break;
423 }
424
425 case AINPUT_EVENT_TYPE_MOTION: {
426 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800427 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800428 break;
429 }
430 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431 return true;
432 }
433
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600434 void interceptKeyBeforeQueueing(const KeyEvent*, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800435
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600436 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600438 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800439 return 0;
440 }
441
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600442 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800443 return false;
444 }
445
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600446 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
447 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700448 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800449 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
450 * essentially a passthrough for notifySwitch.
451 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800452 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800453 }
454
Sean Stoutb4e0a592021-02-23 07:34:53 -0800455 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800456
Prabir Pradhan93f342c2021-03-11 15:05:30 -0800457 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
458 return pid == INJECTOR_PID && uid == INJECTOR_UID;
459 }
Jackal Guof9696682018-10-05 12:23:23 +0800460
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600461 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700462 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700463 mOnPointerDownToken = newToken;
464 }
465
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000466 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800467 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000468 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800469 mPointerCaptureChangedCondition.notify_all();
470 }
471
arthurhungf452d0b2021-01-06 00:19:52 +0800472 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
473 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800474 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800475 mDropTargetWindowToken = token;
476 }
477
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700478 void assertFilterInputEventWasCalledInternal(
479 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700480 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800481 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700482 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800483 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800484 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800485};
486
Michael Wrightd02c5b62014-02-10 15:10:22 -0800487// --- InputDispatcherTest ---
488
489class InputDispatcherTest : public testing::Test {
490protected:
491 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700492 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800493
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000494 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800495 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700496 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Arthur Hungb92218b2018-08-14 12:00:21 +0800497 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000498 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700499 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800500 }
501
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000502 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700503 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800504 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700505 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800506 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700507
508 /**
509 * Used for debugging when writing the test
510 */
511 void dumpDispatcherState() {
512 std::string dump;
513 mDispatcher->dump(dump);
514 std::stringstream ss(dump);
515 std::string to;
516
517 while (std::getline(ss, to, '\n')) {
518 ALOGE("%s", to.c_str());
519 }
520 }
Vishnu Nair958da932020-08-21 17:12:37 -0700521
chaviw3277faf2021-05-19 16:45:23 -0500522 void setFocusedWindow(const sp<WindowInfoHandle>& window,
523 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700524 FocusRequest request;
525 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000526 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700527 if (focusedWindow) {
528 request.focusedToken = focusedWindow->getToken();
529 }
530 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
531 request.displayId = window->getInfo()->displayId;
532 mDispatcher->setFocusedWindow(request);
533 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800534};
535
Michael Wrightd02c5b62014-02-10 15:10:22 -0800536TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
537 KeyEvent event;
538
539 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800540 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
541 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600542 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
543 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800544 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700545 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800546 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800547 << "Should reject key events with undefined action.";
548
549 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800550 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
551 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600552 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800553 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700554 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800555 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800556 << "Should reject key events with ACTION_MULTIPLE.";
557}
558
559TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
560 MotionEvent event;
561 PointerProperties pointerProperties[MAX_POINTERS + 1];
562 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800563 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564 pointerProperties[i].clear();
565 pointerProperties[i].id = i;
566 pointerCoords[i].clear();
567 }
568
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800569 // Some constants commonly used below
570 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
571 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
572 constexpr int32_t metaState = AMETA_NONE;
573 constexpr MotionClassification classification = MotionClassification::NONE;
574
chaviw9eaa22c2020-07-01 16:21:27 -0700575 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800576 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800577 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700578 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
579 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700580 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
581 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700582 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800583 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700584 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800585 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800586 << "Should reject motion events with undefined action.";
587
588 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800589 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700590 AMOTION_EVENT_ACTION_POINTER_DOWN |
591 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700592 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
593 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700594 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500595 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800596 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700597 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800598 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800599 << "Should reject motion events with pointer down index too large.";
600
Garfield Tanfbe732e2020-01-24 11:26:14 -0800601 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700602 AMOTION_EVENT_ACTION_POINTER_DOWN |
603 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700604 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
605 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700606 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500607 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800608 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700609 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800610 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611 << "Should reject motion events with pointer down index too small.";
612
613 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800614 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700615 AMOTION_EVENT_ACTION_POINTER_UP |
616 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700617 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
618 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700619 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500620 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800621 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700622 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800623 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800624 << "Should reject motion events with pointer up index too large.";
625
Garfield Tanfbe732e2020-01-24 11:26:14 -0800626 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700627 AMOTION_EVENT_ACTION_POINTER_UP |
628 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700629 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
630 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700631 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500632 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800633 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700634 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800635 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800636 << "Should reject motion events with pointer up index too small.";
637
638 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800639 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
640 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700641 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700642 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
643 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700644 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800645 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700646 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800647 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800648 << "Should reject motion events with 0 pointers.";
649
Garfield Tanfbe732e2020-01-24 11:26:14 -0800650 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
651 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700652 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700653 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
654 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700655 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800656 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700657 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800658 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800659 << "Should reject motion events with more than MAX_POINTERS pointers.";
660
661 // Rejects motion events with invalid pointer ids.
662 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800663 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
664 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700665 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700666 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
667 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700668 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800669 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700670 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800671 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800672 << "Should reject motion events with pointer ids less than 0.";
673
674 pointerProperties[0].id = MAX_POINTER_ID + 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800675 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
676 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700677 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700678 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
679 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700680 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800681 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700682 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800683 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
685
686 // Rejects motion events with duplicate pointer ids.
687 pointerProperties[0].id = 1;
688 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800689 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
690 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700691 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700692 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
693 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700694 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800695 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700696 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800697 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 << "Should reject motion events with duplicate pointer ids.";
699}
700
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800701/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
702
703TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
704 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800705 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800706 mDispatcher->notifyConfigurationChanged(&args);
707 ASSERT_TRUE(mDispatcher->waitForIdle());
708
709 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
710}
711
712TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800713 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
714 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800715 mDispatcher->notifySwitch(&args);
716
717 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
718 args.policyFlags |= POLICY_FLAG_TRUSTED;
719 mFakePolicy->assertNotifySwitchWasCalled(args);
720}
721
Arthur Hungb92218b2018-08-14 12:00:21 +0800722// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700723static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700724// Default input dispatching timeout if there is no focused application or paused window
725// from which to determine an appropriate dispatching timeout.
726static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
727 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
728 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800729
730class FakeApplicationHandle : public InputApplicationHandle {
731public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700732 FakeApplicationHandle() {
733 mInfo.name = "Fake Application";
734 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500735 mInfo.dispatchingTimeoutMillis =
736 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700737 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800738 virtual ~FakeApplicationHandle() {}
739
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000740 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700741
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500742 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
743 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700744 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800745};
746
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800747class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800748public:
Garfield Tan15601662020-09-22 15:32:38 -0700749 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800750 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700751 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800752 }
753
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800754 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700755 InputEvent* event;
756 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
757 if (!consumeSeq) {
758 return nullptr;
759 }
760 finishEvent(*consumeSeq);
761 return event;
762 }
763
764 /**
765 * Receive an event without acknowledging it.
766 * Return the sequence number that could later be used to send finished signal.
767 */
768 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800769 uint32_t consumeSeq;
770 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800771
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800772 std::chrono::time_point start = std::chrono::steady_clock::now();
773 status_t status = WOULD_BLOCK;
774 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800775 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800776 &event);
777 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
778 if (elapsed > 100ms) {
779 break;
780 }
781 }
782
783 if (status == WOULD_BLOCK) {
784 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700785 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800786 }
787
788 if (status != OK) {
789 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700790 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800791 }
792 if (event == nullptr) {
793 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700794 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800795 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700796 if (outEvent != nullptr) {
797 *outEvent = event;
798 }
799 return consumeSeq;
800 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800801
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700802 /**
803 * To be used together with "receiveEvent" to complete the consumption of an event.
804 */
805 void finishEvent(uint32_t consumeSeq) {
806 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
807 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800808 }
809
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000810 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
811 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
812 ASSERT_EQ(OK, status);
813 }
814
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000815 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
816 std::optional<int32_t> expectedDisplayId,
817 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800818 InputEvent* event = consume();
819
820 ASSERT_NE(nullptr, event) << mName.c_str()
821 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800822 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700823 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800824 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800825
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000826 if (expectedDisplayId.has_value()) {
827 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
828 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800829
Tiger Huang8664f8c2018-10-11 19:14:35 +0800830 switch (expectedEventType) {
831 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800832 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
833 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000834 if (expectedFlags.has_value()) {
835 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
836 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800837 break;
838 }
839 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800840 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000841 assertMotionAction(expectedAction, motionEvent.getAction());
842
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000843 if (expectedFlags.has_value()) {
844 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
845 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800846 break;
847 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100848 case AINPUT_EVENT_TYPE_FOCUS: {
849 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
850 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800851 case AINPUT_EVENT_TYPE_CAPTURE: {
852 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
853 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000854 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
855 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
856 }
arthurhungb89ccb02020-12-30 16:19:01 +0800857 case AINPUT_EVENT_TYPE_DRAG: {
858 FAIL() << "Use 'consumeDragEvent' for DRAG events";
859 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800860 default: {
861 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
862 }
863 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800864 }
865
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100866 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
867 InputEvent* event = consume();
868 ASSERT_NE(nullptr, event) << mName.c_str()
869 << ": consumer should have returned non-NULL event.";
870 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
871 << "Got " << inputEventTypeToString(event->getType())
872 << " event instead of FOCUS event";
873
874 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
875 << mName.c_str() << ": event displayId should always be NONE.";
876
877 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
878 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100879 }
880
Prabir Pradhan99987712020-11-10 18:43:05 -0800881 void consumeCaptureEvent(bool hasCapture) {
882 const InputEvent* event = consume();
883 ASSERT_NE(nullptr, event) << mName.c_str()
884 << ": consumer should have returned non-NULL event.";
885 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
886 << "Got " << inputEventTypeToString(event->getType())
887 << " event instead of CAPTURE event";
888
889 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
890 << mName.c_str() << ": event displayId should always be NONE.";
891
892 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
893 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
894 }
895
arthurhungb89ccb02020-12-30 16:19:01 +0800896 void consumeDragEvent(bool isExiting, float x, float y) {
897 const InputEvent* event = consume();
898 ASSERT_NE(nullptr, event) << mName.c_str()
899 << ": consumer should have returned non-NULL event.";
900 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
901 << "Got " << inputEventTypeToString(event->getType())
902 << " event instead of DRAG event";
903
904 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
905 << mName.c_str() << ": event displayId should always be NONE.";
906
907 const auto& dragEvent = static_cast<const DragEvent&>(*event);
908 EXPECT_EQ(isExiting, dragEvent.isExiting());
909 EXPECT_EQ(x, dragEvent.getX());
910 EXPECT_EQ(y, dragEvent.getY());
911 }
912
Antonio Kantekf16f2832021-09-28 04:39:20 +0000913 void consumeTouchModeEvent(bool inTouchMode) {
914 const InputEvent* event = consume();
915 ASSERT_NE(nullptr, event) << mName.c_str()
916 << ": consumer should have returned non-NULL event.";
917 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
918 << "Got " << inputEventTypeToString(event->getType())
919 << " event instead of TOUCH_MODE event";
920
921 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
922 << mName.c_str() << ": event displayId should always be NONE.";
923 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
924 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
925 }
926
chaviwd1c23182019-12-20 18:44:56 -0800927 void assertNoEvents() {
928 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700929 if (event == nullptr) {
930 return;
931 }
932 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
933 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
934 ADD_FAILURE() << "Received key event "
935 << KeyEvent::actionToString(keyEvent.getAction());
936 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
937 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
938 ADD_FAILURE() << "Received motion event "
939 << MotionEvent::actionToString(motionEvent.getAction());
940 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
941 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
942 ADD_FAILURE() << "Received focus event, hasFocus = "
943 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800944 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
945 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
946 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
947 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000948 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
949 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
950 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
951 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700952 }
953 FAIL() << mName.c_str()
954 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800955 }
956
957 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
958
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800959 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
960
chaviwd1c23182019-12-20 18:44:56 -0800961protected:
962 std::unique_ptr<InputConsumer> mConsumer;
963 PreallocatedInputEventFactory mEventFactory;
964
965 std::string mName;
966};
967
chaviw3277faf2021-05-19 16:45:23 -0500968class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800969public:
970 static const int32_t WIDTH = 600;
971 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800972
Chris Yea209fde2020-07-22 13:54:51 -0700973 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700974 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500975 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800976 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500977 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700978 base::Result<std::unique_ptr<InputChannel>> channel =
979 dispatcher->createInputChannel(name);
980 token = (*channel)->getConnectionToken();
981 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800982 }
983
984 inputApplicationHandle->updateInfo();
985 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
986
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500987 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -0700988 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -0800989 mInfo.name = name;
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));
chaviwd1c23182019-12-20 18:44:56 -08001000 mInfo.ownerPid = INJECTOR_PID;
1001 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -08001002 mInfo.displayId = displayId;
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001003 setVisible(true);
1004 setFocusable(false);
1005 setDupTouchToWallpaper(false);
1006 setPaused(false);
1007 setTrustedOverlay(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
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001019 void setTouchable(bool touchable) {
1020 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1021 }
chaviwd1c23182019-12-20 18:44:56 -08001022
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001023 void setFocusable(bool focusable) {
1024 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1025 }
1026
1027 void setVisible(bool visible) {
1028 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1029 }
Vishnu Nair958da932020-08-21 17:12:37 -07001030
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001031 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001032 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001033 }
1034
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001035 void setPaused(bool paused) {
1036 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1037 }
1038
1039 void setTouchModal(bool touchModal) {
1040 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCH_MODAL, !touchModal);
1041 }
1042
1043 void setSplitTouch(bool splitTouch) {
1044 mInfo.setInputConfig(WindowInfo::InputConfig::SPLIT_TOUCH, splitTouch);
1045 }
1046
1047 void setSlippery(bool slippery) {
1048 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1049 }
1050
1051 void setWatchOutsideTouch(bool watchOutside) {
1052 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1053 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001054
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001055 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1056
chaviw3277faf2021-05-19 16:45:23 -05001057 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001058
Bernardo Rufino7393d172021-02-26 13:56:11 +00001059 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1060
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001061 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001062 mInfo.frameLeft = frame.left;
1063 mInfo.frameTop = frame.top;
1064 mInfo.frameRight = frame.right;
1065 mInfo.frameBottom = frame.bottom;
1066 mInfo.touchableRegion.clear();
1067 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001068
1069 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1070 ui::Transform translate;
1071 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1072 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001073 }
1074
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001075 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1076
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001077 void setIsWallpaper(bool isWallpaper) {
1078 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1079 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001080
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001081 void setDupTouchToWallpaper(bool hasWallpaper) {
1082 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1083 }
chaviwd1c23182019-12-20 18:44:56 -08001084
Prabir Pradhand65552b2021-10-07 11:23:50 -07001085 void setInputFeatures(Flags<WindowInfo::Feature> features) { mInfo.inputFeatures = features; }
1086
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001087 void setTrustedOverlay(bool trustedOverlay) {
1088 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1089 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001090
chaviw9eaa22c2020-07-01 16:21:27 -07001091 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1092 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1093 }
1094
1095 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001096
yunho.shinf4a80b82020-11-16 21:13:57 +09001097 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1098
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001099 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1100 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1101 expectedFlags);
1102 }
1103
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001104 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1105 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1106 }
1107
Svet Ganov5d3bc372020-01-26 23:11:07 -08001108 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001109 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001110 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1111 expectedFlags);
1112 }
1113
1114 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001115 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001116 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1117 expectedFlags);
1118 }
1119
1120 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001121 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001122 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1123 }
1124
1125 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1126 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001127 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1128 expectedFlags);
1129 }
1130
Svet Ganov5d3bc372020-01-26 23:11:07 -08001131 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001132 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1133 int32_t expectedFlags = 0) {
1134 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1135 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001136 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1137 }
1138
1139 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001140 int32_t expectedFlags = 0) {
1141 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1142 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001143 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1144 }
1145
1146 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001147 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001148 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1149 expectedFlags);
1150 }
1151
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001152 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1153 int32_t expectedFlags = 0) {
1154 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1155 expectedFlags);
1156 }
1157
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001158 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1159 int32_t expectedFlags = 0) {
1160 InputEvent* event = consume();
1161 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1162 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1163 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1164 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1165 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1166 }
1167
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001168 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1169 ASSERT_NE(mInputReceiver, nullptr)
1170 << "Cannot consume events from a window with no receiver";
1171 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1172 }
1173
Prabir Pradhan99987712020-11-10 18:43:05 -08001174 void consumeCaptureEvent(bool hasCapture) {
1175 ASSERT_NE(mInputReceiver, nullptr)
1176 << "Cannot consume events from a window with no receiver";
1177 mInputReceiver->consumeCaptureEvent(hasCapture);
1178 }
1179
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001180 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1181 std::optional<int32_t> expectedDisplayId,
1182 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001183 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1184 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1185 expectedFlags);
1186 }
1187
arthurhungb89ccb02020-12-30 16:19:01 +08001188 void consumeDragEvent(bool isExiting, float x, float y) {
1189 mInputReceiver->consumeDragEvent(isExiting, x, y);
1190 }
1191
Antonio Kantekf16f2832021-09-28 04:39:20 +00001192 void consumeTouchModeEvent(bool inTouchMode) {
1193 ASSERT_NE(mInputReceiver, nullptr)
1194 << "Cannot consume events from a window with no receiver";
1195 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1196 }
1197
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001198 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001199 if (mInputReceiver == nullptr) {
1200 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1201 return std::nullopt;
1202 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001203 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001204 }
1205
1206 void finishEvent(uint32_t sequenceNum) {
1207 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1208 mInputReceiver->finishEvent(sequenceNum);
1209 }
1210
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001211 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1212 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1213 mInputReceiver->sendTimeline(inputEventId, timeline);
1214 }
1215
chaviwaf87b3e2019-10-01 16:59:28 -07001216 InputEvent* consume() {
1217 if (mInputReceiver == nullptr) {
1218 return nullptr;
1219 }
1220 return mInputReceiver->consume();
1221 }
1222
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001223 MotionEvent* consumeMotion() {
1224 InputEvent* event = consume();
1225 if (event == nullptr) {
1226 ADD_FAILURE() << "Consume failed : no event";
1227 return nullptr;
1228 }
1229 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1230 ADD_FAILURE() << "Instead of motion event, got "
1231 << inputEventTypeToString(event->getType());
1232 return nullptr;
1233 }
1234 return static_cast<MotionEvent*>(event);
1235 }
1236
Arthur Hungb92218b2018-08-14 12:00:21 +08001237 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001238 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001239 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001240 return; // Can't receive events if the window does not have input channel
1241 }
1242 ASSERT_NE(nullptr, mInputReceiver)
1243 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001244 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001245 }
1246
chaviwaf87b3e2019-10-01 16:59:28 -07001247 sp<IBinder> getToken() { return mInfo.token; }
1248
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001249 const std::string& getName() { return mName; }
1250
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001251 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1252 mInfo.ownerPid = ownerPid;
1253 mInfo.ownerUid = ownerUid;
1254 }
1255
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001256 void destroyReceiver() { mInputReceiver = nullptr; }
1257
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001258 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1259
chaviwd1c23182019-12-20 18:44:56 -08001260private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001261 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001262 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001263 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001264};
1265
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001266std::atomic<int32_t> FakeWindowHandle::sId{1};
1267
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001268static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001269 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001270 int32_t displayId = ADISPLAY_ID_NONE,
1271 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001272 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1273 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001274 KeyEvent event;
1275 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1276
1277 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001278 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001279 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1280 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001281
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001282 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1283 if (!allowKeyRepeat) {
1284 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1285 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001286 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001287 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001288 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001289}
1290
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001291static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001292 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001293 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1294}
1295
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001296// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1297// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1298// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001299static InputEventInjectionResult injectKeyDownNoRepeat(
1300 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001301 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1302 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1303 /* allowKeyRepeat */ false);
1304}
1305
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001306static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001307 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001308 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1309}
1310
Garfield Tandf26e862020-07-01 20:18:19 -07001311class PointerBuilder {
1312public:
1313 PointerBuilder(int32_t id, int32_t toolType) {
1314 mProperties.clear();
1315 mProperties.id = id;
1316 mProperties.toolType = toolType;
1317 mCoords.clear();
1318 }
1319
1320 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1321
1322 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1323
1324 PointerBuilder& axis(int32_t axis, float value) {
1325 mCoords.setAxisValue(axis, value);
1326 return *this;
1327 }
1328
1329 PointerProperties buildProperties() const { return mProperties; }
1330
1331 PointerCoords buildCoords() const { return mCoords; }
1332
1333private:
1334 PointerProperties mProperties;
1335 PointerCoords mCoords;
1336};
1337
1338class MotionEventBuilder {
1339public:
1340 MotionEventBuilder(int32_t action, int32_t source) {
1341 mAction = action;
1342 mSource = source;
1343 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1344 }
1345
1346 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1347 mEventTime = eventTime;
1348 return *this;
1349 }
1350
1351 MotionEventBuilder& displayId(int32_t displayId) {
1352 mDisplayId = displayId;
1353 return *this;
1354 }
1355
1356 MotionEventBuilder& actionButton(int32_t actionButton) {
1357 mActionButton = actionButton;
1358 return *this;
1359 }
1360
arthurhung6d4bed92021-03-17 11:59:33 +08001361 MotionEventBuilder& buttonState(int32_t buttonState) {
1362 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001363 return *this;
1364 }
1365
1366 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1367 mRawXCursorPosition = rawXCursorPosition;
1368 return *this;
1369 }
1370
1371 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1372 mRawYCursorPosition = rawYCursorPosition;
1373 return *this;
1374 }
1375
1376 MotionEventBuilder& pointer(PointerBuilder pointer) {
1377 mPointers.push_back(pointer);
1378 return *this;
1379 }
1380
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001381 MotionEventBuilder& addFlag(uint32_t flags) {
1382 mFlags |= flags;
1383 return *this;
1384 }
1385
Garfield Tandf26e862020-07-01 20:18:19 -07001386 MotionEvent build() {
1387 std::vector<PointerProperties> pointerProperties;
1388 std::vector<PointerCoords> pointerCoords;
1389 for (const PointerBuilder& pointer : mPointers) {
1390 pointerProperties.push_back(pointer.buildProperties());
1391 pointerCoords.push_back(pointer.buildCoords());
1392 }
1393
1394 // Set mouse cursor position for the most common cases to avoid boilerplate.
1395 if (mSource == AINPUT_SOURCE_MOUSE &&
1396 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1397 mPointers.size() == 1) {
1398 mRawXCursorPosition = pointerCoords[0].getX();
1399 mRawYCursorPosition = pointerCoords[0].getY();
1400 }
1401
1402 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001403 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001404 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001405 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001406 mButtonState, MotionClassification::NONE, identityTransform,
1407 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001408 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1409 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001410
1411 return event;
1412 }
1413
1414private:
1415 int32_t mAction;
1416 int32_t mSource;
1417 nsecs_t mEventTime;
1418 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1419 int32_t mActionButton{0};
1420 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001421 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001422 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1423 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1424
1425 std::vector<PointerBuilder> mPointers;
1426};
1427
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001428static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001429 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001430 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001431 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001432 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1433 injectionTimeout,
1434 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1435}
1436
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001437static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001438 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001439 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001440 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001441 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1442 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001443 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001444 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001445 MotionEvent event = MotionEventBuilder(action, source)
1446 .displayId(displayId)
1447 .eventTime(eventTime)
1448 .rawXCursorPosition(cursorPosition.x)
1449 .rawYCursorPosition(cursorPosition.y)
1450 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1451 .x(position.x)
1452 .y(position.y))
1453 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001454
1455 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001456 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001457}
1458
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001459static InputEventInjectionResult injectMotionDown(
1460 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1461 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001462 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001463}
1464
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001465static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001466 int32_t source, int32_t displayId,
1467 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001468 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001469}
1470
Jackal Guof9696682018-10-05 12:23:23 +08001471static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1472 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1473 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001474 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1475 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1476 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001477
1478 return args;
1479}
1480
chaviwd1c23182019-12-20 18:44:56 -08001481static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1482 const std::vector<PointF>& points) {
1483 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001484 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1485 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1486 }
1487
chaviwd1c23182019-12-20 18:44:56 -08001488 PointerProperties pointerProperties[pointerCount];
1489 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001490
chaviwd1c23182019-12-20 18:44:56 -08001491 for (size_t i = 0; i < pointerCount; i++) {
1492 pointerProperties[i].clear();
1493 pointerProperties[i].id = i;
1494 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001495
chaviwd1c23182019-12-20 18:44:56 -08001496 pointerCoords[i].clear();
1497 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1498 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1499 }
Jackal Guof9696682018-10-05 12:23:23 +08001500
1501 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1502 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001503 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001504 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1505 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001506 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1507 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001508 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1509 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001510
1511 return args;
1512}
1513
chaviwd1c23182019-12-20 18:44:56 -08001514static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1515 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1516}
1517
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001518static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1519 const PointerCaptureRequest& request) {
1520 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001521}
1522
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001523/**
1524 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1525 * broken channel.
1526 */
1527TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1528 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1529 sp<FakeWindowHandle> window =
1530 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1531 ADISPLAY_ID_DEFAULT);
1532
1533 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1534
1535 // Window closes its channel, but the window remains.
1536 window->destroyReceiver();
1537 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1538}
1539
Arthur Hungb92218b2018-08-14 12:00:21 +08001540TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001541 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001542 sp<FakeWindowHandle> window =
1543 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001544
Arthur Hung72d8dc32020-03-28 00:48:39 +00001545 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001546 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1547 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1548 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001549
1550 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001551 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001552}
1553
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001554TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1555 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1556 sp<FakeWindowHandle> window =
1557 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1558
1559 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1560 // Inject a MotionEvent to an unknown display.
1561 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1562 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1563 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1564
1565 // Window should receive motion event.
1566 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1567}
1568
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001569/**
1570 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1571 * To ensure that window receives only events that were directly inside of it, add
1572 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1573 * when finding touched windows.
1574 * This test serves as a sanity check for the next test, where setInputWindows is
1575 * called twice.
1576 */
1577TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001578 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001579 sp<FakeWindowHandle> window =
1580 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1581 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001582 window->setTouchModal(false);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001583
1584 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001585 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001586 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1587 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001588 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001589
1590 // Window should receive motion event.
1591 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1592}
1593
1594/**
1595 * Calling setInputWindows twice, with the same info, should not cause any issues.
1596 * To ensure that window receives only events that were directly inside of it, add
1597 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1598 * when finding touched windows.
1599 */
1600TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001601 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001602 sp<FakeWindowHandle> window =
1603 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1604 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001605 window->setTouchModal(false);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001606
1607 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1608 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001609 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001610 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1611 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001612 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001613
1614 // Window should receive motion event.
1615 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1616}
1617
Arthur Hungb92218b2018-08-14 12:00:21 +08001618// The foreground window should receive the first touch down event.
1619TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001620 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001621 sp<FakeWindowHandle> windowTop =
1622 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1623 sp<FakeWindowHandle> windowSecond =
1624 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001625
Arthur Hung72d8dc32020-03-28 00:48:39 +00001626 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001627 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1628 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1629 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001630
1631 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001632 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001633 windowSecond->assertNoEvents();
1634}
1635
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001636/**
1637 * Two windows: A top window, and a wallpaper behind the window.
1638 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1639 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001640 * 1. foregroundWindow <-- dup touch to wallpaper
1641 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001642 */
1643TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1644 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1645 sp<FakeWindowHandle> foregroundWindow =
1646 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001647 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001648 sp<FakeWindowHandle> wallpaperWindow =
1649 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001650 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001651 constexpr int expectedWallpaperFlags =
1652 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1653
1654 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1655 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1656 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1657 {100, 200}))
1658 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1659
1660 // Both foreground window and its wallpaper should receive the touch down
1661 foregroundWindow->consumeMotionDown();
1662 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1663
1664 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1665 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1666 ADISPLAY_ID_DEFAULT, {110, 200}))
1667 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1668
1669 foregroundWindow->consumeMotionMove();
1670 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1671
1672 // Now the foreground window goes away, but the wallpaper stays
1673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1674 foregroundWindow->consumeMotionCancel();
1675 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1676 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1677}
1678
1679/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001680 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1681 * with the following differences:
1682 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1683 * clean up the connection.
1684 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1685 * Ensure that there's no crash in the dispatcher.
1686 */
1687TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1688 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1689 sp<FakeWindowHandle> foregroundWindow =
1690 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001691 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001692 sp<FakeWindowHandle> wallpaperWindow =
1693 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001694 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001695 constexpr int expectedWallpaperFlags =
1696 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1697
1698 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1699 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1700 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1701 {100, 200}))
1702 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1703
1704 // Both foreground window and its wallpaper should receive the touch down
1705 foregroundWindow->consumeMotionDown();
1706 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1707
1708 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1709 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1710 ADISPLAY_ID_DEFAULT, {110, 200}))
1711 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1712
1713 foregroundWindow->consumeMotionMove();
1714 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1715
1716 // Wallpaper closes its channel, but the window remains.
1717 wallpaperWindow->destroyReceiver();
1718 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1719
1720 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1721 // is no longer valid.
1722 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1723 foregroundWindow->consumeMotionCancel();
1724}
1725
1726/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001727 * A single window that receives touch (on top), and a wallpaper window underneath it.
1728 * The top window gets a multitouch gesture.
1729 * Ensure that wallpaper gets the same gesture.
1730 */
1731TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1732 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1733 sp<FakeWindowHandle> window =
1734 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001735 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001736
1737 sp<FakeWindowHandle> wallpaperWindow =
1738 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001739 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001740 constexpr int expectedWallpaperFlags =
1741 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1742
1743 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1744
1745 // Touch down on top window
1746 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1747 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1748 {100, 100}))
1749 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1750
1751 // Both top window and its wallpaper should receive the touch down
1752 window->consumeMotionDown();
1753 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1754
1755 // Second finger down on the top window
1756 const MotionEvent secondFingerDownEvent =
1757 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1758 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1759 AINPUT_SOURCE_TOUCHSCREEN)
1760 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1761 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1762 .x(100)
1763 .y(100))
1764 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1765 .x(150)
1766 .y(150))
1767 .build();
1768 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1769 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1770 InputEventInjectionSync::WAIT_FOR_RESULT))
1771 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1772
1773 window->consumeMotionPointerDown(1 /* pointerIndex */);
1774 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1775 expectedWallpaperFlags);
1776 window->assertNoEvents();
1777 wallpaperWindow->assertNoEvents();
1778}
1779
1780/**
1781 * Two windows: a window on the left and window on the right.
1782 * A third window, wallpaper, is behind both windows, and spans both top windows.
1783 * The first touch down goes to the left window. A second pointer touches down on the right window.
1784 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1785 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1786 * ACTION_POINTER_DOWN(1).
1787 */
1788TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1789 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1790 sp<FakeWindowHandle> leftWindow =
1791 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1792 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001793 leftWindow->setTouchModal(false);
1794 leftWindow->setSplitTouch(true);
1795 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001796
1797 sp<FakeWindowHandle> rightWindow =
1798 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1799 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001800 rightWindow->setTouchModal(false);
1801 rightWindow->setSplitTouch(true);
1802 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001803
1804 sp<FakeWindowHandle> wallpaperWindow =
1805 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1806 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001807 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001808 constexpr int expectedWallpaperFlags =
1809 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1810
1811 mDispatcher->setInputWindows(
1812 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1813
1814 // Touch down on left window
1815 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1816 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1817 {100, 100}))
1818 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1819
1820 // Both foreground window and its wallpaper should receive the touch down
1821 leftWindow->consumeMotionDown();
1822 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1823
1824 // Second finger down on the right window
1825 const MotionEvent secondFingerDownEvent =
1826 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1827 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1828 AINPUT_SOURCE_TOUCHSCREEN)
1829 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1830 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1831 .x(100)
1832 .y(100))
1833 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1834 .x(300)
1835 .y(100))
1836 .build();
1837 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1838 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1839 InputEventInjectionSync::WAIT_FOR_RESULT))
1840 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1841
1842 leftWindow->consumeMotionMove();
1843 // Since the touch is split, right window gets ACTION_DOWN
1844 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1845 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1846 expectedWallpaperFlags);
1847
1848 // Now, leftWindow, which received the first finger, disappears.
1849 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1850 leftWindow->consumeMotionCancel();
1851 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1852 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1853
1854 // The pointer that's still down on the right window moves, and goes to the right window only.
1855 // As far as the dispatcher's concerned though, both pointers are still present.
1856 const MotionEvent secondFingerMoveEvent =
1857 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1858 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1859 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1860 .x(100)
1861 .y(100))
1862 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1863 .x(310)
1864 .y(110))
1865 .build();
1866 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1867 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1868 InputEventInjectionSync::WAIT_FOR_RESULT));
1869 rightWindow->consumeMotionMove();
1870
1871 leftWindow->assertNoEvents();
1872 rightWindow->assertNoEvents();
1873 wallpaperWindow->assertNoEvents();
1874}
1875
Garfield Tandf26e862020-07-01 20:18:19 -07001876TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001877 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001878 sp<FakeWindowHandle> windowLeft =
1879 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1880 windowLeft->setFrame(Rect(0, 0, 600, 800));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001881 windowLeft->setTouchModal(false);
Garfield Tandf26e862020-07-01 20:18:19 -07001882 sp<FakeWindowHandle> windowRight =
1883 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1884 windowRight->setFrame(Rect(600, 0, 1200, 800));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001885 windowRight->setTouchModal(false);
Garfield Tandf26e862020-07-01 20:18:19 -07001886
1887 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1888
1889 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1890
1891 // Start cursor position in right window so that we can move the cursor to left window.
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_HOVER_MOVE,
1895 AINPUT_SOURCE_MOUSE)
1896 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1897 .x(900)
1898 .y(400))
1899 .build()));
1900 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1901 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1902 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1903 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1904
1905 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001906 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001907 injectMotionEvent(mDispatcher,
1908 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1909 AINPUT_SOURCE_MOUSE)
1910 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1911 .x(300)
1912 .y(400))
1913 .build()));
1914 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1915 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1916 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1917 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1918 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1919 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1920
1921 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001922 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001923 injectMotionEvent(mDispatcher,
1924 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1925 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1926 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1927 .x(300)
1928 .y(400))
1929 .build()));
1930 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1931
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001932 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001933 injectMotionEvent(mDispatcher,
1934 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1935 AINPUT_SOURCE_MOUSE)
1936 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1937 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1938 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1939 .x(300)
1940 .y(400))
1941 .build()));
1942 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1943 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1944
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001945 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001946 injectMotionEvent(mDispatcher,
1947 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1948 AINPUT_SOURCE_MOUSE)
1949 .buttonState(0)
1950 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1951 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1952 .x(300)
1953 .y(400))
1954 .build()));
1955 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1956 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1957
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001958 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001959 injectMotionEvent(mDispatcher,
1960 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1961 .buttonState(0)
1962 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1963 .x(300)
1964 .y(400))
1965 .build()));
1966 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1967
1968 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001970 injectMotionEvent(mDispatcher,
1971 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1972 AINPUT_SOURCE_MOUSE)
1973 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1974 .x(900)
1975 .y(400))
1976 .build()));
1977 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1978 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1979 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1980 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1981 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1982 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1983}
1984
1985// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1986// directly in this test.
1987TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001988 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001989 sp<FakeWindowHandle> window =
1990 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1991 window->setFrame(Rect(0, 0, 1200, 800));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001992 window->setTouchModal(false);
Garfield Tandf26e862020-07-01 20:18:19 -07001993
1994 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1995
1996 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1997
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001998 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001999 injectMotionEvent(mDispatcher,
2000 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2001 AINPUT_SOURCE_MOUSE)
2002 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2003 .x(300)
2004 .y(400))
2005 .build()));
2006 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2007 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2008
2009 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002010 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002011 injectMotionEvent(mDispatcher,
2012 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2013 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2014 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2015 .x(300)
2016 .y(400))
2017 .build()));
2018 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2019
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002020 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002021 injectMotionEvent(mDispatcher,
2022 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2023 AINPUT_SOURCE_MOUSE)
2024 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2025 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2026 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2027 .x(300)
2028 .y(400))
2029 .build()));
2030 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2031 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2032
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002033 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002034 injectMotionEvent(mDispatcher,
2035 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2036 AINPUT_SOURCE_MOUSE)
2037 .buttonState(0)
2038 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2039 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2040 .x(300)
2041 .y(400))
2042 .build()));
2043 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2044 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2045
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002046 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002047 injectMotionEvent(mDispatcher,
2048 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2049 .buttonState(0)
2050 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2051 .x(300)
2052 .y(400))
2053 .build()));
2054 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2055
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002056 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002057 injectMotionEvent(mDispatcher,
2058 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2059 AINPUT_SOURCE_MOUSE)
2060 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2061 .x(300)
2062 .y(400))
2063 .build()));
2064 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2065 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2066}
2067
Garfield Tan00f511d2019-06-12 16:55:40 -07002068TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002069 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002070
2071 sp<FakeWindowHandle> windowLeft =
2072 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2073 windowLeft->setFrame(Rect(0, 0, 600, 800));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002074 windowLeft->setTouchModal(false);
Garfield Tan00f511d2019-06-12 16:55:40 -07002075 sp<FakeWindowHandle> windowRight =
2076 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2077 windowRight->setFrame(Rect(600, 0, 1200, 800));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002078 windowRight->setTouchModal(false);
Garfield Tan00f511d2019-06-12 16:55:40 -07002079
2080 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2081
Arthur Hung72d8dc32020-03-28 00:48:39 +00002082 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002083
2084 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2085 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002086 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002087 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002088 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002089 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002090 windowRight->assertNoEvents();
2091}
2092
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002093TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002094 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002095 sp<FakeWindowHandle> window =
2096 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002097 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002098
Arthur Hung72d8dc32020-03-28 00:48:39 +00002099 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002100 setFocusedWindow(window);
2101
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002102 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002103
2104 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2105 mDispatcher->notifyKey(&keyArgs);
2106
2107 // Window should receive key down event.
2108 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2109
2110 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2111 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002112 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002113 mDispatcher->notifyDeviceReset(&args);
2114 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2115 AKEY_EVENT_FLAG_CANCELED);
2116}
2117
2118TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002119 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002120 sp<FakeWindowHandle> window =
2121 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2122
Arthur Hung72d8dc32020-03-28 00:48:39 +00002123 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002124
2125 NotifyMotionArgs motionArgs =
2126 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2127 ADISPLAY_ID_DEFAULT);
2128 mDispatcher->notifyMotion(&motionArgs);
2129
2130 // Window should receive motion down event.
2131 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2132
2133 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2134 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002135 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002136 mDispatcher->notifyDeviceReset(&args);
2137 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2138 0 /*expectedFlags*/);
2139}
2140
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002141/**
2142 * Ensure the correct coordinate spaces are used by InputDispatcher.
2143 *
2144 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2145 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2146 * space.
2147 */
2148class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2149public:
2150 void SetUp() override {
2151 InputDispatcherTest::SetUp();
2152 mDisplayInfos.clear();
2153 mWindowInfos.clear();
2154 }
2155
2156 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2157 gui::DisplayInfo info;
2158 info.displayId = displayId;
2159 info.transform = transform;
2160 mDisplayInfos.push_back(std::move(info));
2161 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2162 }
2163
2164 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2165 mWindowInfos.push_back(*windowHandle->getInfo());
2166 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2167 }
2168
2169 // Set up a test scenario where the display has a scaled projection and there are two windows
2170 // on the display.
2171 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2172 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2173 // respectively.
2174 ui::Transform displayTransform;
2175 displayTransform.set(2, 0, 0, 4);
2176 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2177
2178 std::shared_ptr<FakeApplicationHandle> application =
2179 std::make_shared<FakeApplicationHandle>();
2180
2181 // Add two windows to the display. Their frames are represented in the display space.
2182 sp<FakeWindowHandle> firstWindow =
2183 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002184 firstWindow->setTouchModal(false);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002185 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2186 addWindow(firstWindow);
2187
2188 sp<FakeWindowHandle> secondWindow =
2189 new FakeWindowHandle(application, mDispatcher, "Second Window",
2190 ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002191 secondWindow->setTouchModal(false);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002192 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2193 addWindow(secondWindow);
2194 return {std::move(firstWindow), std::move(secondWindow)};
2195 }
2196
2197private:
2198 std::vector<gui::DisplayInfo> mDisplayInfos;
2199 std::vector<gui::WindowInfo> mWindowInfos;
2200};
2201
2202TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2203 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2204 // Send down to the first window. The point is represented in the display space. The point is
2205 // selected so that if the hit test was done with the transform applied to it, then it would
2206 // end up in the incorrect window.
2207 NotifyMotionArgs downMotionArgs =
2208 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2209 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2210 mDispatcher->notifyMotion(&downMotionArgs);
2211
2212 firstWindow->consumeMotionDown();
2213 secondWindow->assertNoEvents();
2214}
2215
2216// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2217// the event should be treated as being in the logical display space.
2218TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2219 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2220 // Send down to the first window. The point is represented in the logical display space. The
2221 // point is selected so that if the hit test was done in logical display space, then it would
2222 // end up in the incorrect window.
2223 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2224 PointF{75 * 2, 55 * 4});
2225
2226 firstWindow->consumeMotionDown();
2227 secondWindow->assertNoEvents();
2228}
2229
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002230// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2231// event should be treated as being in the logical display space.
2232TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2233 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2234
2235 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2236 ui::Transform injectedEventTransform;
2237 injectedEventTransform.set(matrix);
2238 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2239 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2240
2241 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2242 .displayId(ADISPLAY_ID_DEFAULT)
2243 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2244 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2245 .x(untransformedPoint.x)
2246 .y(untransformedPoint.y))
2247 .build();
2248 event.transform(matrix);
2249
2250 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2251 InputEventInjectionSync::WAIT_FOR_RESULT);
2252
2253 firstWindow->consumeMotionDown();
2254 secondWindow->assertNoEvents();
2255}
2256
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002257TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2258 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2259
2260 // Send down to the second window.
2261 NotifyMotionArgs downMotionArgs =
2262 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2263 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2264 mDispatcher->notifyMotion(&downMotionArgs);
2265
2266 firstWindow->assertNoEvents();
2267 const MotionEvent* event = secondWindow->consumeMotion();
2268 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2269
2270 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2271 EXPECT_EQ(300, event->getRawX(0));
2272 EXPECT_EQ(880, event->getRawY(0));
2273
2274 // Ensure that the x and y values are in the window's coordinate space.
2275 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2276 // the logical display space. This will be the origin of the window space.
2277 EXPECT_EQ(100, event->getX(0));
2278 EXPECT_EQ(80, event->getY(0));
2279}
2280
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002281using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2282 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002283
2284class TransferTouchFixture : public InputDispatcherTest,
2285 public ::testing::WithParamInterface<TransferFunction> {};
2286
2287TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002288 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002289
2290 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002291 sp<FakeWindowHandle> firstWindow =
2292 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2293 sp<FakeWindowHandle> secondWindow =
2294 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002295
2296 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002297 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002298
2299 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002300 NotifyMotionArgs downMotionArgs =
2301 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2302 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002303 mDispatcher->notifyMotion(&downMotionArgs);
2304 // Only the first window should get the down event
2305 firstWindow->consumeMotionDown();
2306 secondWindow->assertNoEvents();
2307
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002308 // Transfer touch to the second window
2309 TransferFunction f = GetParam();
2310 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2311 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002312 // The first window gets cancel and the second gets down
2313 firstWindow->consumeMotionCancel();
2314 secondWindow->consumeMotionDown();
2315
2316 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002317 NotifyMotionArgs upMotionArgs =
2318 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2319 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002320 mDispatcher->notifyMotion(&upMotionArgs);
2321 // The first window gets no events and the second gets up
2322 firstWindow->assertNoEvents();
2323 secondWindow->consumeMotionUp();
2324}
2325
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002326TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002327 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002328
2329 PointF touchPoint = {10, 10};
2330
2331 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002332 sp<FakeWindowHandle> firstWindow =
2333 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2334 sp<FakeWindowHandle> secondWindow =
2335 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002336
2337 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002338 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002339
2340 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002341 NotifyMotionArgs downMotionArgs =
2342 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2343 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002344 mDispatcher->notifyMotion(&downMotionArgs);
2345 // Only the first window should get the down event
2346 firstWindow->consumeMotionDown();
2347 secondWindow->assertNoEvents();
2348
2349 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002350 NotifyMotionArgs pointerDownMotionArgs =
2351 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2352 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2353 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2354 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002355 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2356 // Only the first window should get the pointer down event
2357 firstWindow->consumeMotionPointerDown(1);
2358 secondWindow->assertNoEvents();
2359
2360 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002361 TransferFunction f = GetParam();
2362 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2363 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002364 // The first window gets cancel and the second gets down and pointer down
2365 firstWindow->consumeMotionCancel();
2366 secondWindow->consumeMotionDown();
2367 secondWindow->consumeMotionPointerDown(1);
2368
2369 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002370 NotifyMotionArgs pointerUpMotionArgs =
2371 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2372 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2373 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2374 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002375 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2376 // The first window gets nothing and the second gets pointer up
2377 firstWindow->assertNoEvents();
2378 secondWindow->consumeMotionPointerUp(1);
2379
2380 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002381 NotifyMotionArgs upMotionArgs =
2382 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2383 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002384 mDispatcher->notifyMotion(&upMotionArgs);
2385 // The first window gets nothing and the second gets up
2386 firstWindow->assertNoEvents();
2387 secondWindow->consumeMotionUp();
2388}
2389
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002390// For the cases of single pointer touch and two pointers non-split touch, the api's
2391// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2392// for the case where there are multiple pointers split across several windows.
2393INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2394 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002395 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2396 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002397 return dispatcher->transferTouch(destChannelToken);
2398 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002399 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2400 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002401 return dispatcher->transferTouchFocus(from, to,
2402 false /*isDragAndDrop*/);
2403 }));
2404
Svet Ganov5d3bc372020-01-26 23:11:07 -08002405TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002406 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002407
2408 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002409 sp<FakeWindowHandle> firstWindow =
2410 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002411 firstWindow->setFrame(Rect(0, 0, 600, 400));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002412 firstWindow->setTouchModal(false);
2413 firstWindow->setSplitTouch(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002414
2415 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002416 sp<FakeWindowHandle> secondWindow =
2417 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002418 secondWindow->setFrame(Rect(0, 400, 600, 800));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002419 secondWindow->setTouchModal(false);
2420 secondWindow->setSplitTouch(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002421
2422 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002423 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002424
2425 PointF pointInFirst = {300, 200};
2426 PointF pointInSecond = {300, 600};
2427
2428 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002429 NotifyMotionArgs firstDownMotionArgs =
2430 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2431 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002432 mDispatcher->notifyMotion(&firstDownMotionArgs);
2433 // Only the first window should get the down event
2434 firstWindow->consumeMotionDown();
2435 secondWindow->assertNoEvents();
2436
2437 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002438 NotifyMotionArgs secondDownMotionArgs =
2439 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2440 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2441 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2442 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002443 mDispatcher->notifyMotion(&secondDownMotionArgs);
2444 // The first window gets a move and the second a down
2445 firstWindow->consumeMotionMove();
2446 secondWindow->consumeMotionDown();
2447
2448 // Transfer touch focus to the second window
2449 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2450 // The first window gets cancel and the new gets pointer down (it already saw down)
2451 firstWindow->consumeMotionCancel();
2452 secondWindow->consumeMotionPointerDown(1);
2453
2454 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002455 NotifyMotionArgs pointerUpMotionArgs =
2456 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2457 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2458 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2459 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002460 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2461 // The first window gets nothing and the second gets pointer up
2462 firstWindow->assertNoEvents();
2463 secondWindow->consumeMotionPointerUp(1);
2464
2465 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002466 NotifyMotionArgs upMotionArgs =
2467 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2468 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002469 mDispatcher->notifyMotion(&upMotionArgs);
2470 // The first window gets nothing and the second gets up
2471 firstWindow->assertNoEvents();
2472 secondWindow->consumeMotionUp();
2473}
2474
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002475// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2476// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2477// touch is not supported, so the touch should continue on those windows and the transferred-to
2478// window should get nothing.
2479TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2480 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2481
2482 // Create a non touch modal window that supports split touch
2483 sp<FakeWindowHandle> firstWindow =
2484 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2485 firstWindow->setFrame(Rect(0, 0, 600, 400));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002486 firstWindow->setTouchModal(false);
2487 firstWindow->setSplitTouch(true);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002488
2489 // Create a non touch modal window that supports split touch
2490 sp<FakeWindowHandle> secondWindow =
2491 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2492 secondWindow->setFrame(Rect(0, 400, 600, 800));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002493 secondWindow->setTouchModal(false);
2494 secondWindow->setSplitTouch(true);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002495
2496 // Add the windows to the dispatcher
2497 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2498
2499 PointF pointInFirst = {300, 200};
2500 PointF pointInSecond = {300, 600};
2501
2502 // Send down to the first window
2503 NotifyMotionArgs firstDownMotionArgs =
2504 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2505 ADISPLAY_ID_DEFAULT, {pointInFirst});
2506 mDispatcher->notifyMotion(&firstDownMotionArgs);
2507 // Only the first window should get the down event
2508 firstWindow->consumeMotionDown();
2509 secondWindow->assertNoEvents();
2510
2511 // Send down to the second window
2512 NotifyMotionArgs secondDownMotionArgs =
2513 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2514 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2515 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2516 {pointInFirst, pointInSecond});
2517 mDispatcher->notifyMotion(&secondDownMotionArgs);
2518 // The first window gets a move and the second a down
2519 firstWindow->consumeMotionMove();
2520 secondWindow->consumeMotionDown();
2521
2522 // Transfer touch focus to the second window
2523 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2524 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2525 ASSERT_FALSE(transferred);
2526 firstWindow->assertNoEvents();
2527 secondWindow->assertNoEvents();
2528
2529 // The rest of the dispatch should proceed as normal
2530 // Send pointer up to the second window
2531 NotifyMotionArgs pointerUpMotionArgs =
2532 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2533 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2534 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2535 {pointInFirst, pointInSecond});
2536 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2537 // The first window gets MOVE and the second gets pointer up
2538 firstWindow->consumeMotionMove();
2539 secondWindow->consumeMotionUp();
2540
2541 // Send up event to the first window
2542 NotifyMotionArgs upMotionArgs =
2543 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2544 ADISPLAY_ID_DEFAULT);
2545 mDispatcher->notifyMotion(&upMotionArgs);
2546 // The first window gets nothing and the second gets up
2547 firstWindow->consumeMotionUp();
2548 secondWindow->assertNoEvents();
2549}
2550
Arthur Hungabbb9d82021-09-01 14:52:30 +00002551// This case will create two windows and one mirrored window on the default display and mirror
2552// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2553// the windows info of second display before default display.
2554TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2555 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2556 sp<FakeWindowHandle> firstWindowInPrimary =
2557 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2558 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002559 firstWindowInPrimary->setTouchModal(false);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002560 sp<FakeWindowHandle> secondWindowInPrimary =
2561 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2562 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002563 secondWindowInPrimary->setTouchModal(false);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002564
2565 sp<FakeWindowHandle> mirrorWindowInPrimary =
2566 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2567 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002568 mirrorWindowInPrimary->setTouchModal(false);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002569
2570 sp<FakeWindowHandle> firstWindowInSecondary =
2571 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2572 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002573 firstWindowInSecondary->setTouchModal(false);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002574
2575 sp<FakeWindowHandle> secondWindowInSecondary =
2576 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2577 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002578 secondWindowInPrimary->setTouchModal(false);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002579
2580 // Update window info, let it find window handle of second display first.
2581 mDispatcher->setInputWindows(
2582 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2583 {ADISPLAY_ID_DEFAULT,
2584 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2585
2586 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2587 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2588 {50, 50}))
2589 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2590
2591 // Window should receive motion event.
2592 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2593
2594 // Transfer touch focus
2595 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2596 secondWindowInPrimary->getToken()));
2597 // The first window gets cancel.
2598 firstWindowInPrimary->consumeMotionCancel();
2599 secondWindowInPrimary->consumeMotionDown();
2600
2601 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2602 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2603 ADISPLAY_ID_DEFAULT, {150, 50}))
2604 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2605 firstWindowInPrimary->assertNoEvents();
2606 secondWindowInPrimary->consumeMotionMove();
2607
2608 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2609 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2610 {150, 50}))
2611 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2612 firstWindowInPrimary->assertNoEvents();
2613 secondWindowInPrimary->consumeMotionUp();
2614}
2615
2616// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2617// 'transferTouch' api.
2618TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2619 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2620 sp<FakeWindowHandle> firstWindowInPrimary =
2621 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2622 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002623 firstWindowInPrimary->setTouchModal(false);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002624 sp<FakeWindowHandle> secondWindowInPrimary =
2625 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2626 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002627 secondWindowInPrimary->setTouchModal(false);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002628
2629 sp<FakeWindowHandle> mirrorWindowInPrimary =
2630 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2631 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002632 mirrorWindowInPrimary->setTouchModal(false);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002633
2634 sp<FakeWindowHandle> firstWindowInSecondary =
2635 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2636 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002637 firstWindowInSecondary->setTouchModal(false);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002638
2639 sp<FakeWindowHandle> secondWindowInSecondary =
2640 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2641 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002642 secondWindowInPrimary->setTouchModal(false);
Arthur Hungabbb9d82021-09-01 14:52:30 +00002643
2644 // Update window info, let it find window handle of second display first.
2645 mDispatcher->setInputWindows(
2646 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2647 {ADISPLAY_ID_DEFAULT,
2648 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2649
2650 // Touch on second display.
2651 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2652 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2653 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2654
2655 // Window should receive motion event.
2656 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2657
2658 // Transfer touch focus
2659 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2660
2661 // The first window gets cancel.
2662 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2663 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2664
2665 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2666 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2667 SECOND_DISPLAY_ID, {150, 50}))
2668 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2669 firstWindowInPrimary->assertNoEvents();
2670 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2671
2672 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2673 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2674 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2675 firstWindowInPrimary->assertNoEvents();
2676 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2677}
2678
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002679TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002680 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002681 sp<FakeWindowHandle> window =
2682 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2683
Vishnu Nair47074b82020-08-14 11:54:47 -07002684 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002685 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002686 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002687
2688 window->consumeFocusEvent(true);
2689
2690 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2691 mDispatcher->notifyKey(&keyArgs);
2692
2693 // Window should receive key down event.
2694 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2695}
2696
2697TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002698 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002699 sp<FakeWindowHandle> window =
2700 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2701
Arthur Hung72d8dc32020-03-28 00:48:39 +00002702 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002703
2704 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2705 mDispatcher->notifyKey(&keyArgs);
2706 mDispatcher->waitForIdle();
2707
2708 window->assertNoEvents();
2709}
2710
2711// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2712TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002713 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002714 sp<FakeWindowHandle> window =
2715 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2716
Arthur Hung72d8dc32020-03-28 00:48:39 +00002717 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002718
2719 // Send key
2720 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2721 mDispatcher->notifyKey(&keyArgs);
2722 // Send motion
2723 NotifyMotionArgs motionArgs =
2724 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2725 ADISPLAY_ID_DEFAULT);
2726 mDispatcher->notifyMotion(&motionArgs);
2727
2728 // Window should receive only the motion event
2729 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2730 window->assertNoEvents(); // Key event or focus event will not be received
2731}
2732
arthurhungea3f4fc2020-12-21 23:18:53 +08002733TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2734 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2735
2736 // Create first non touch modal window that supports split touch
2737 sp<FakeWindowHandle> firstWindow =
2738 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2739 firstWindow->setFrame(Rect(0, 0, 600, 400));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002740 firstWindow->setTouchModal(false);
2741 firstWindow->setSplitTouch(true);
arthurhungea3f4fc2020-12-21 23:18:53 +08002742
2743 // Create second non touch modal window that supports split touch
2744 sp<FakeWindowHandle> secondWindow =
2745 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2746 secondWindow->setFrame(Rect(0, 400, 600, 800));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08002747 secondWindow->setTouchModal(false);
2748 secondWindow->setSplitTouch(true);
arthurhungea3f4fc2020-12-21 23:18:53 +08002749
2750 // Add the windows to the dispatcher
2751 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2752
2753 PointF pointInFirst = {300, 200};
2754 PointF pointInSecond = {300, 600};
2755
2756 // Send down to the first window
2757 NotifyMotionArgs firstDownMotionArgs =
2758 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2759 ADISPLAY_ID_DEFAULT, {pointInFirst});
2760 mDispatcher->notifyMotion(&firstDownMotionArgs);
2761 // Only the first window should get the down event
2762 firstWindow->consumeMotionDown();
2763 secondWindow->assertNoEvents();
2764
2765 // Send down to the second window
2766 NotifyMotionArgs secondDownMotionArgs =
2767 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2768 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2769 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2770 {pointInFirst, pointInSecond});
2771 mDispatcher->notifyMotion(&secondDownMotionArgs);
2772 // The first window gets a move and the second a down
2773 firstWindow->consumeMotionMove();
2774 secondWindow->consumeMotionDown();
2775
2776 // Send pointer cancel to the second window
2777 NotifyMotionArgs pointerUpMotionArgs =
2778 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2779 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2780 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2781 {pointInFirst, pointInSecond});
2782 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2783 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2784 // The first window gets move and the second gets cancel.
2785 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2786 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2787
2788 // Send up event.
2789 NotifyMotionArgs upMotionArgs =
2790 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2791 ADISPLAY_ID_DEFAULT);
2792 mDispatcher->notifyMotion(&upMotionArgs);
2793 // The first window gets up and the second gets nothing.
2794 firstWindow->consumeMotionUp();
2795 secondWindow->assertNoEvents();
2796}
2797
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002798TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2799 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2800
2801 sp<FakeWindowHandle> window =
2802 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2803 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2804 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2805 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2806 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2807
2808 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2809 window->assertNoEvents();
2810 mDispatcher->waitForIdle();
2811}
2812
chaviwd1c23182019-12-20 18:44:56 -08002813class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002814public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002815 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002816 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07002817 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002818 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002819 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002820 }
2821
chaviwd1c23182019-12-20 18:44:56 -08002822 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2823
2824 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2825 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2826 expectedDisplayId, expectedFlags);
2827 }
2828
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002829 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2830
2831 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2832
chaviwd1c23182019-12-20 18:44:56 -08002833 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2834 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2835 expectedDisplayId, expectedFlags);
2836 }
2837
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002838 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2839 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2840 expectedDisplayId, expectedFlags);
2841 }
2842
chaviwd1c23182019-12-20 18:44:56 -08002843 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2844 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2845 expectedDisplayId, expectedFlags);
2846 }
2847
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002848 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2849 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2850 expectedDisplayId, expectedFlags);
2851 }
2852
Arthur Hungfbfa5722021-11-16 02:45:54 +00002853 void consumeMotionPointerDown(int32_t pointerIdx) {
2854 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2855 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2856 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2857 0 /*expectedFlags*/);
2858 }
2859
Evan Rosky84f07f02021-04-16 10:42:42 -07002860 MotionEvent* consumeMotion() {
2861 InputEvent* event = mInputReceiver->consume();
2862 if (!event) {
2863 ADD_FAILURE() << "No event was produced";
2864 return nullptr;
2865 }
2866 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2867 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2868 return nullptr;
2869 }
2870 return static_cast<MotionEvent*>(event);
2871 }
2872
chaviwd1c23182019-12-20 18:44:56 -08002873 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2874
2875private:
2876 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002877};
2878
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002879using InputDispatcherMonitorTest = InputDispatcherTest;
2880
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002881/**
2882 * Two entities that receive touch: A window, and a global monitor.
2883 * The touch goes to the window, and then the window disappears.
2884 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2885 * for the monitor, as well.
2886 * 1. foregroundWindow
2887 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2888 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002889TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002890 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2891 sp<FakeWindowHandle> window =
2892 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2893
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002894 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002895
2896 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2897 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2898 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2899 {100, 200}))
2900 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2901
2902 // Both the foreground window and the global monitor should receive the touch down
2903 window->consumeMotionDown();
2904 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2905
2906 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2907 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2908 ADISPLAY_ID_DEFAULT, {110, 200}))
2909 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2910
2911 window->consumeMotionMove();
2912 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2913
2914 // Now the foreground window goes away
2915 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2916 window->consumeMotionCancel();
2917 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2918
2919 // If more events come in, there will be no more foreground window to send them to. This will
2920 // cause a cancel for the monitor, as well.
2921 ASSERT_EQ(InputEventInjectionResult::FAILED,
2922 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2923 ADISPLAY_ID_DEFAULT, {120, 200}))
2924 << "Injection should fail because the window was removed";
2925 window->assertNoEvents();
2926 // Global monitor now gets the cancel
2927 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2928}
2929
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002930TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002931 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002932 sp<FakeWindowHandle> window =
2933 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002934 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002935
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002936 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002937
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002938 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002939 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002940 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002941 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002942 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002943}
2944
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002945TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
2946 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002947
Chris Yea209fde2020-07-22 13:54:51 -07002948 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002949 sp<FakeWindowHandle> window =
2950 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002951 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002952
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002953 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002954 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002955 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002956 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002957 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002958
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002959 // Pilfer pointers from the monitor.
2960 // This should not do anything and the window should continue to receive events.
2961 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00002962
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002963 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002964 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2965 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002966 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002967
2968 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2969 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002970}
2971
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002972TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07002973 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2974 sp<FakeWindowHandle> window =
2975 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2976 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2977 window->setWindowOffset(20, 40);
2978 window->setWindowTransform(0, 1, -1, 0);
2979
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002980 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07002981
2982 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2983 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2984 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2985 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2986 MotionEvent* event = monitor.consumeMotion();
2987 // Even though window has transform, gesture monitor must not.
2988 ASSERT_EQ(ui::Transform(), event->getTransform());
2989}
2990
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002991TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002992 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002993 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00002994
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002995 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00002996 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002997 << "Injection should fail if there is a monitor, but no touchable window";
2998 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00002999}
3000
chaviw81e2bb92019-12-18 15:03:51 -08003001TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003002 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08003003 sp<FakeWindowHandle> window =
3004 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3005
Arthur Hung72d8dc32020-03-28 00:48:39 +00003006 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003007
3008 NotifyMotionArgs motionArgs =
3009 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3010 ADISPLAY_ID_DEFAULT);
3011
3012 mDispatcher->notifyMotion(&motionArgs);
3013 // Window should receive motion down event.
3014 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3015
3016 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003017 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003018 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3019 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3020 motionArgs.pointerCoords[0].getX() - 10);
3021
3022 mDispatcher->notifyMotion(&motionArgs);
3023 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3024 0 /*expectedFlags*/);
3025}
3026
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003027/**
3028 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3029 * the device default right away. In the test scenario, we check both the default value,
3030 * and the action of enabling / disabling.
3031 */
3032TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003033 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003034 sp<FakeWindowHandle> window =
3035 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003036 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003037
3038 // Set focused application.
3039 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003040 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003041
3042 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003043 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003044 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003045 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3046
3047 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003048 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003049 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003050 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3051
3052 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003053 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3054 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003055 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003056 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003057 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003058 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003059 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3060
3061 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003062 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003063 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003064 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3065
3066 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003067 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3068 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003069 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003070 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003071 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003072 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003073 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3074
3075 window->assertNoEvents();
3076}
3077
Gang Wange9087892020-01-07 12:17:14 -05003078TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003079 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003080 sp<FakeWindowHandle> window =
3081 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3082
3083 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003084 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003085
Arthur Hung72d8dc32020-03-28 00:48:39 +00003086 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003087 setFocusedWindow(window);
3088
Gang Wange9087892020-01-07 12:17:14 -05003089 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3090
3091 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3092 mDispatcher->notifyKey(&keyArgs);
3093
3094 InputEvent* event = window->consume();
3095 ASSERT_NE(event, nullptr);
3096
3097 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3098 ASSERT_NE(verified, nullptr);
3099 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3100
3101 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3102 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3103 ASSERT_EQ(keyArgs.source, verified->source);
3104 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3105
3106 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3107
3108 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003109 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003110 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003111 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3112 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3113 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3114 ASSERT_EQ(0, verifiedKey.repeatCount);
3115}
3116
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003117TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003118 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003119 sp<FakeWindowHandle> window =
3120 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3121
3122 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3123
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003124 ui::Transform transform;
3125 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3126
3127 gui::DisplayInfo displayInfo;
3128 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3129 displayInfo.transform = transform;
3130
3131 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003132
3133 NotifyMotionArgs motionArgs =
3134 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3135 ADISPLAY_ID_DEFAULT);
3136 mDispatcher->notifyMotion(&motionArgs);
3137
3138 InputEvent* event = window->consume();
3139 ASSERT_NE(event, nullptr);
3140
3141 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3142 ASSERT_NE(verified, nullptr);
3143 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3144
3145 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3146 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3147 EXPECT_EQ(motionArgs.source, verified->source);
3148 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3149
3150 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3151
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003152 const vec2 rawXY =
3153 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3154 motionArgs.pointerCoords[0].getXYValue());
3155 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3156 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003157 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003158 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003159 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003160 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3161 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3162}
3163
chaviw09c8d2d2020-08-24 15:48:26 -07003164/**
3165 * Ensure that separate calls to sign the same data are generating the same key.
3166 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3167 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3168 * tests.
3169 */
3170TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3171 KeyEvent event = getTestKeyEvent();
3172 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3173
3174 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3175 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3176 ASSERT_EQ(hmac1, hmac2);
3177}
3178
3179/**
3180 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3181 */
3182TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3183 KeyEvent event = getTestKeyEvent();
3184 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3185 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3186
3187 verifiedEvent.deviceId += 1;
3188 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3189
3190 verifiedEvent.source += 1;
3191 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3192
3193 verifiedEvent.eventTimeNanos += 1;
3194 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3195
3196 verifiedEvent.displayId += 1;
3197 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3198
3199 verifiedEvent.action += 1;
3200 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3201
3202 verifiedEvent.downTimeNanos += 1;
3203 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3204
3205 verifiedEvent.flags += 1;
3206 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3207
3208 verifiedEvent.keyCode += 1;
3209 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3210
3211 verifiedEvent.scanCode += 1;
3212 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3213
3214 verifiedEvent.metaState += 1;
3215 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3216
3217 verifiedEvent.repeatCount += 1;
3218 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3219}
3220
Vishnu Nair958da932020-08-21 17:12:37 -07003221TEST_F(InputDispatcherTest, SetFocusedWindow) {
3222 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3223 sp<FakeWindowHandle> windowTop =
3224 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3225 sp<FakeWindowHandle> windowSecond =
3226 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3227 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3228
3229 // Top window is also focusable but is not granted focus.
3230 windowTop->setFocusable(true);
3231 windowSecond->setFocusable(true);
3232 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3233 setFocusedWindow(windowSecond);
3234
3235 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003236 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3237 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003238
3239 // Focused window should receive event.
3240 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3241 windowTop->assertNoEvents();
3242}
3243
3244TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3245 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3246 sp<FakeWindowHandle> window =
3247 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3248 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3249
3250 window->setFocusable(true);
3251 // Release channel for window is no longer valid.
3252 window->releaseChannel();
3253 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3254 setFocusedWindow(window);
3255
3256 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003257 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3258 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003259
3260 // window channel is invalid, so it should not receive any input event.
3261 window->assertNoEvents();
3262}
3263
3264TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3265 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3266 sp<FakeWindowHandle> window =
3267 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3268 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3269
3270 // Window is not focusable.
3271 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3272 setFocusedWindow(window);
3273
3274 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003275 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3276 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003277
3278 // window is invalid, so it should not receive any input event.
3279 window->assertNoEvents();
3280}
3281
3282TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3283 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3284 sp<FakeWindowHandle> windowTop =
3285 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3286 sp<FakeWindowHandle> windowSecond =
3287 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3288 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3289
3290 windowTop->setFocusable(true);
3291 windowSecond->setFocusable(true);
3292 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3293 setFocusedWindow(windowTop);
3294 windowTop->consumeFocusEvent(true);
3295
3296 setFocusedWindow(windowSecond, windowTop);
3297 windowSecond->consumeFocusEvent(true);
3298 windowTop->consumeFocusEvent(false);
3299
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003300 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3301 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003302
3303 // Focused window should receive event.
3304 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3305}
3306
3307TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3308 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3309 sp<FakeWindowHandle> windowTop =
3310 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3311 sp<FakeWindowHandle> windowSecond =
3312 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3313 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3314
3315 windowTop->setFocusable(true);
3316 windowSecond->setFocusable(true);
3317 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3318 setFocusedWindow(windowSecond, windowTop);
3319
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003320 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3321 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003322
3323 // Event should be dropped.
3324 windowTop->assertNoEvents();
3325 windowSecond->assertNoEvents();
3326}
3327
3328TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3329 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3330 sp<FakeWindowHandle> window =
3331 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3332 sp<FakeWindowHandle> previousFocusedWindow =
3333 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3334 ADISPLAY_ID_DEFAULT);
3335 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3336
3337 window->setFocusable(true);
3338 previousFocusedWindow->setFocusable(true);
3339 window->setVisible(false);
3340 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3341 setFocusedWindow(previousFocusedWindow);
3342 previousFocusedWindow->consumeFocusEvent(true);
3343
3344 // Requesting focus on invisible window takes focus from currently focused window.
3345 setFocusedWindow(window);
3346 previousFocusedWindow->consumeFocusEvent(false);
3347
3348 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003349 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003350 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003351 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003352
3353 // Window does not get focus event or key down.
3354 window->assertNoEvents();
3355
3356 // Window becomes visible.
3357 window->setVisible(true);
3358 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3359
3360 // Window receives focus event.
3361 window->consumeFocusEvent(true);
3362 // Focused window receives key down.
3363 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3364}
3365
Vishnu Nair599f1412021-06-21 10:39:58 -07003366TEST_F(InputDispatcherTest, DisplayRemoved) {
3367 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3368 sp<FakeWindowHandle> window =
3369 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3370 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3371
3372 // window is granted focus.
3373 window->setFocusable(true);
3374 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3375 setFocusedWindow(window);
3376 window->consumeFocusEvent(true);
3377
3378 // When a display is removed window loses focus.
3379 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3380 window->consumeFocusEvent(false);
3381}
3382
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003383/**
3384 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3385 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3386 * of the 'slipperyEnterWindow'.
3387 *
3388 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3389 * a way so that the touched location is no longer covered by the top window.
3390 *
3391 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3392 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3393 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3394 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3395 * with ACTION_DOWN).
3396 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3397 * window moved itself away from the touched location and had Flag::SLIPPERY.
3398 *
3399 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3400 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3401 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3402 *
3403 * In this test, we ensure that the event received by the bottom window has
3404 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3405 */
3406TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3407 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3408 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3409
3410 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3411 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3412
3413 sp<FakeWindowHandle> slipperyExitWindow =
3414 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003415 slipperyExitWindow->setTouchModal(false);
3416 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003417 // Make sure this one overlaps the bottom window
3418 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3419 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3420 // one. Windows with the same owner are not considered to be occluding each other.
3421 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3422
3423 sp<FakeWindowHandle> slipperyEnterWindow =
3424 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3425 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3426
3427 mDispatcher->setInputWindows(
3428 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3429
3430 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3431 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3432 ADISPLAY_ID_DEFAULT, {{50, 50}});
3433 mDispatcher->notifyMotion(&args);
3434 slipperyExitWindow->consumeMotionDown();
3435 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3436 mDispatcher->setInputWindows(
3437 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3438
3439 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3440 ADISPLAY_ID_DEFAULT, {{51, 51}});
3441 mDispatcher->notifyMotion(&args);
3442
3443 slipperyExitWindow->consumeMotionCancel();
3444
3445 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3446 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3447}
3448
Garfield Tan1c7bc862020-01-28 13:24:04 -08003449class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3450protected:
3451 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3452 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3453
Chris Yea209fde2020-07-22 13:54:51 -07003454 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003455 sp<FakeWindowHandle> mWindow;
3456
3457 virtual void SetUp() override {
3458 mFakePolicy = new FakeInputDispatcherPolicy();
3459 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003460 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003461 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3462 ASSERT_EQ(OK, mDispatcher->start());
3463
3464 setUpWindow();
3465 }
3466
3467 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003468 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003469 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3470
Vishnu Nair47074b82020-08-14 11:54:47 -07003471 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003472 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003473 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003474 mWindow->consumeFocusEvent(true);
3475 }
3476
Chris Ye2ad95392020-09-01 13:44:44 -07003477 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003478 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003479 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003480 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3481 mDispatcher->notifyKey(&keyArgs);
3482
3483 // Window should receive key down event.
3484 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3485 }
3486
3487 void expectKeyRepeatOnce(int32_t repeatCount) {
3488 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3489 InputEvent* repeatEvent = mWindow->consume();
3490 ASSERT_NE(nullptr, repeatEvent);
3491
3492 uint32_t eventType = repeatEvent->getType();
3493 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3494
3495 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3496 uint32_t eventAction = repeatKeyEvent->getAction();
3497 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3498 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3499 }
3500
Chris Ye2ad95392020-09-01 13:44:44 -07003501 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003502 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003503 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003504 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3505 mDispatcher->notifyKey(&keyArgs);
3506
3507 // Window should receive key down event.
3508 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3509 0 /*expectedFlags*/);
3510 }
3511};
3512
3513TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003514 sendAndConsumeKeyDown(1 /* deviceId */);
3515 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3516 expectKeyRepeatOnce(repeatCount);
3517 }
3518}
3519
3520TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3521 sendAndConsumeKeyDown(1 /* deviceId */);
3522 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3523 expectKeyRepeatOnce(repeatCount);
3524 }
3525 sendAndConsumeKeyDown(2 /* deviceId */);
3526 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003527 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3528 expectKeyRepeatOnce(repeatCount);
3529 }
3530}
3531
3532TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003533 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003534 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003535 sendAndConsumeKeyUp(1 /* deviceId */);
3536 mWindow->assertNoEvents();
3537}
3538
3539TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3540 sendAndConsumeKeyDown(1 /* deviceId */);
3541 expectKeyRepeatOnce(1 /*repeatCount*/);
3542 sendAndConsumeKeyDown(2 /* deviceId */);
3543 expectKeyRepeatOnce(1 /*repeatCount*/);
3544 // Stale key up from device 1.
3545 sendAndConsumeKeyUp(1 /* deviceId */);
3546 // Device 2 is still down, keep repeating
3547 expectKeyRepeatOnce(2 /*repeatCount*/);
3548 expectKeyRepeatOnce(3 /*repeatCount*/);
3549 // Device 2 key up
3550 sendAndConsumeKeyUp(2 /* deviceId */);
3551 mWindow->assertNoEvents();
3552}
3553
3554TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3555 sendAndConsumeKeyDown(1 /* deviceId */);
3556 expectKeyRepeatOnce(1 /*repeatCount*/);
3557 sendAndConsumeKeyDown(2 /* deviceId */);
3558 expectKeyRepeatOnce(1 /*repeatCount*/);
3559 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3560 sendAndConsumeKeyUp(2 /* deviceId */);
3561 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003562 mWindow->assertNoEvents();
3563}
3564
liushenxiang42232912021-05-21 20:24:09 +08003565TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3566 sendAndConsumeKeyDown(DEVICE_ID);
3567 expectKeyRepeatOnce(1 /*repeatCount*/);
3568 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3569 mDispatcher->notifyDeviceReset(&args);
3570 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3571 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3572 mWindow->assertNoEvents();
3573}
3574
Garfield Tan1c7bc862020-01-28 13:24:04 -08003575TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003576 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003577 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3578 InputEvent* repeatEvent = mWindow->consume();
3579 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3580 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3581 IdGenerator::getSource(repeatEvent->getId()));
3582 }
3583}
3584
3585TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003586 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003587
3588 std::unordered_set<int32_t> idSet;
3589 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3590 InputEvent* repeatEvent = mWindow->consume();
3591 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3592 int32_t id = repeatEvent->getId();
3593 EXPECT_EQ(idSet.end(), idSet.find(id));
3594 idSet.insert(id);
3595 }
3596}
3597
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003598/* Test InputDispatcher for MultiDisplay */
3599class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3600public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003601 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003602 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003603
Chris Yea209fde2020-07-22 13:54:51 -07003604 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003605 windowInPrimary =
3606 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003607
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003608 // Set focus window for primary display, but focused display would be second one.
3609 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003610 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003611 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003612 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003613 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003614
Chris Yea209fde2020-07-22 13:54:51 -07003615 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003616 windowInSecondary =
3617 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003618 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003619 // Set focus display to second one.
3620 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3621 // Set focus window for second display.
3622 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003623 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003624 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003625 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003626 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003627 }
3628
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003629 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003630 InputDispatcherTest::TearDown();
3631
Chris Yea209fde2020-07-22 13:54:51 -07003632 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003633 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003634 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003635 windowInSecondary.clear();
3636 }
3637
3638protected:
Chris Yea209fde2020-07-22 13:54:51 -07003639 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003640 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003641 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003642 sp<FakeWindowHandle> windowInSecondary;
3643};
3644
3645TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3646 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003647 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3648 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3649 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003650 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003651 windowInSecondary->assertNoEvents();
3652
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003653 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003654 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3655 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3656 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003657 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003658 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003659}
3660
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003661TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003662 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003663 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3664 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003665 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003666 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003667 windowInSecondary->assertNoEvents();
3668
3669 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003670 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003671 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003672 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003673 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003674
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003675 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003676 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003677
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003678 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003679 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3680 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003681
3682 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003683 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003684 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003685 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003686 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003687 windowInSecondary->assertNoEvents();
3688}
3689
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003690// Test per-display input monitors for motion event.
3691TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003692 FakeMonitorReceiver monitorInPrimary =
3693 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3694 FakeMonitorReceiver monitorInSecondary =
3695 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003696
3697 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003698 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3699 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3700 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003701 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003702 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003703 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003704 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003705
3706 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003707 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3708 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3709 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003710 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003711 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003712 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003713 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003714
3715 // Test inject a non-pointer motion event.
3716 // If specific a display, it will dispatch to the focused window of particular display,
3717 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003718 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3719 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3720 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003721 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003722 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003723 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003724 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003725}
3726
3727// Test per-display input monitors for key event.
3728TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003729 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003730 FakeMonitorReceiver monitorInPrimary =
3731 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3732 FakeMonitorReceiver monitorInSecondary =
3733 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003734
3735 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003736 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3737 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003738 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003739 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003740 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003741 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003742}
3743
Vishnu Nair958da932020-08-21 17:12:37 -07003744TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3745 sp<FakeWindowHandle> secondWindowInPrimary =
3746 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3747 secondWindowInPrimary->setFocusable(true);
3748 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3749 setFocusedWindow(secondWindowInPrimary);
3750 windowInPrimary->consumeFocusEvent(false);
3751 secondWindowInPrimary->consumeFocusEvent(true);
3752
3753 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003754 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3755 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003756 windowInPrimary->assertNoEvents();
3757 windowInSecondary->assertNoEvents();
3758 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3759}
3760
Arthur Hungdfd528e2021-12-08 13:23:04 +00003761TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3762 FakeMonitorReceiver monitorInPrimary =
3763 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3764 FakeMonitorReceiver monitorInSecondary =
3765 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3766
3767 // Test touch down on primary display.
3768 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3769 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3770 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3771 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3772 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3773
3774 // Test touch down on second display.
3775 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3776 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3777 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3778 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3779 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3780
3781 // Trigger cancel touch.
3782 mDispatcher->cancelCurrentTouch();
3783 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3784 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3785 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3786 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3787
3788 // Test inject a move motion event, no window/monitor should receive the event.
3789 ASSERT_EQ(InputEventInjectionResult::FAILED,
3790 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3791 ADISPLAY_ID_DEFAULT, {110, 200}))
3792 << "Inject motion event should return InputEventInjectionResult::FAILED";
3793 windowInPrimary->assertNoEvents();
3794 monitorInPrimary.assertNoEvents();
3795
3796 ASSERT_EQ(InputEventInjectionResult::FAILED,
3797 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3798 SECOND_DISPLAY_ID, {110, 200}))
3799 << "Inject motion event should return InputEventInjectionResult::FAILED";
3800 windowInSecondary->assertNoEvents();
3801 monitorInSecondary.assertNoEvents();
3802}
3803
Jackal Guof9696682018-10-05 12:23:23 +08003804class InputFilterTest : public InputDispatcherTest {
3805protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003806 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3807 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003808 NotifyMotionArgs motionArgs;
3809
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003810 motionArgs =
3811 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003812 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003813 motionArgs =
3814 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003815 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003816 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003817 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003818 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3819 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003820 } else {
3821 mFakePolicy->assertFilterInputEventWasNotCalled();
3822 }
3823 }
3824
3825 void testNotifyKey(bool expectToBeFiltered) {
3826 NotifyKeyArgs keyArgs;
3827
3828 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3829 mDispatcher->notifyKey(&keyArgs);
3830 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3831 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003832 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003833
3834 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003835 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003836 } else {
3837 mFakePolicy->assertFilterInputEventWasNotCalled();
3838 }
3839 }
3840};
3841
3842// Test InputFilter for MotionEvent
3843TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3844 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3845 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3846 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3847
3848 // Enable InputFilter
3849 mDispatcher->setInputFilterEnabled(true);
3850 // Test touch on both primary and second display, and check if both events are filtered.
3851 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3852 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3853
3854 // Disable InputFilter
3855 mDispatcher->setInputFilterEnabled(false);
3856 // Test touch on both primary and second display, and check if both events aren't filtered.
3857 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3858 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3859}
3860
3861// Test InputFilter for KeyEvent
3862TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3863 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3864 testNotifyKey(/*expectToBeFiltered*/ false);
3865
3866 // Enable InputFilter
3867 mDispatcher->setInputFilterEnabled(true);
3868 // Send a key event, and check if it is filtered.
3869 testNotifyKey(/*expectToBeFiltered*/ true);
3870
3871 // Disable InputFilter
3872 mDispatcher->setInputFilterEnabled(false);
3873 // Send a key event, and check if it isn't filtered.
3874 testNotifyKey(/*expectToBeFiltered*/ false);
3875}
3876
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003877// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3878// logical display coordinate space.
3879TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3880 ui::Transform firstDisplayTransform;
3881 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3882 ui::Transform secondDisplayTransform;
3883 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3884
3885 std::vector<gui::DisplayInfo> displayInfos(2);
3886 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3887 displayInfos[0].transform = firstDisplayTransform;
3888 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3889 displayInfos[1].transform = secondDisplayTransform;
3890
3891 mDispatcher->onWindowInfosChanged({}, displayInfos);
3892
3893 // Enable InputFilter
3894 mDispatcher->setInputFilterEnabled(true);
3895
3896 // Ensure the correct transforms are used for the displays.
3897 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3898 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3899}
3900
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003901class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3902protected:
3903 virtual void SetUp() override {
3904 InputDispatcherTest::SetUp();
3905
3906 /**
3907 * We don't need to enable input filter to test the injected event policy, but we enabled it
3908 * here to make the tests more realistic, since this policy only matters when inputfilter is
3909 * on.
3910 */
3911 mDispatcher->setInputFilterEnabled(true);
3912
3913 std::shared_ptr<InputApplicationHandle> application =
3914 std::make_shared<FakeApplicationHandle>();
3915 mWindow =
3916 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3917
3918 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3919 mWindow->setFocusable(true);
3920 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3921 setFocusedWindow(mWindow);
3922 mWindow->consumeFocusEvent(true);
3923 }
3924
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003925 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3926 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003927 KeyEvent event;
3928
3929 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3930 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3931 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3932 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3933 const int32_t additionalPolicyFlags =
3934 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3935 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3936 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3937 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3938 policyFlags | additionalPolicyFlags));
3939
3940 InputEvent* received = mWindow->consume();
3941 ASSERT_NE(nullptr, received);
3942 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003943 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3944 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3945 ASSERT_EQ(flags, keyEvent.getFlags());
3946 }
3947
3948 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3949 int32_t flags) {
3950 MotionEvent event;
3951 PointerProperties pointerProperties[1];
3952 PointerCoords pointerCoords[1];
3953 pointerProperties[0].clear();
3954 pointerProperties[0].id = 0;
3955 pointerCoords[0].clear();
3956 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3957 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3958
3959 ui::Transform identityTransform;
3960 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3961 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3962 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3963 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3964 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003965 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003966 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003967 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3968
3969 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3970 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3971 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3972 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3973 policyFlags | additionalPolicyFlags));
3974
3975 InputEvent* received = mWindow->consume();
3976 ASSERT_NE(nullptr, received);
3977 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3978 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3979 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3980 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003981 }
3982
3983private:
3984 sp<FakeWindowHandle> mWindow;
3985};
3986
3987TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003988 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3989 // filter. Without it, the event will no different from a regularly injected event, and the
3990 // injected device id will be overwritten.
3991 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3992 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003993}
3994
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003995TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003996 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003997 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3998 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3999}
4000
4001TEST_F(InputFilterInjectionPolicyTest,
4002 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4003 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4004 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4005 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004006}
4007
4008TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4009 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004010 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004011}
4012
chaviwfd6d3512019-03-25 13:23:49 -07004013class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004014 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004015 InputDispatcherTest::SetUp();
4016
Chris Yea209fde2020-07-22 13:54:51 -07004017 std::shared_ptr<FakeApplicationHandle> application =
4018 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004019 mUnfocusedWindow =
4020 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004021 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4022 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4023 // window.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004024 mUnfocusedWindow->setTouchModal(false);
chaviwfd6d3512019-03-25 13:23:49 -07004025
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004026 mFocusedWindow =
4027 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4028 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004029 mFocusedWindow->setTouchModal(false);
chaviwfd6d3512019-03-25 13:23:49 -07004030
4031 // Set focused application.
4032 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004033 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004034
4035 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004036 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004037 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004038 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004039 }
4040
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004041 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004042 InputDispatcherTest::TearDown();
4043
4044 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004045 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004046 }
4047
4048protected:
4049 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004050 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004051 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004052};
4053
4054// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4055// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4056// the onPointerDownOutsideFocus callback.
4057TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004058 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004059 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4060 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004061 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004062 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004063
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004064 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004065 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4066}
4067
4068// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4069// DOWN on the window that doesn't have focus. Ensure no window received the
4070// onPointerDownOutsideFocus callback.
4071TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004072 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004073 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004074 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004075 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004076
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004077 ASSERT_TRUE(mDispatcher->waitForIdle());
4078 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004079}
4080
4081// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4082// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4083TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004084 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4085 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004086 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004087 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004088
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004089 ASSERT_TRUE(mDispatcher->waitForIdle());
4090 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004091}
4092
4093// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4094// DOWN on the window that already has focus. Ensure no window received the
4095// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004096TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004097 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004098 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004099 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004100 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004101 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004102
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004103 ASSERT_TRUE(mDispatcher->waitForIdle());
4104 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004105}
4106
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004107// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4108// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4109TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4110 const MotionEvent event =
4111 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4112 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4113 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4114 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4115 .build();
4116 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4117 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4118 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4119
4120 ASSERT_TRUE(mDispatcher->waitForIdle());
4121 mFakePolicy->assertOnPointerDownWasNotCalled();
4122 // Ensure that the unfocused window did not receive any FOCUS events.
4123 mUnfocusedWindow->assertNoEvents();
4124}
4125
chaviwaf87b3e2019-10-01 16:59:28 -07004126// These tests ensures we can send touch events to a single client when there are multiple input
4127// windows that point to the same client token.
4128class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4129 virtual void SetUp() override {
4130 InputDispatcherTest::SetUp();
4131
Chris Yea209fde2020-07-22 13:54:51 -07004132 std::shared_ptr<FakeApplicationHandle> application =
4133 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004134 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4135 ADISPLAY_ID_DEFAULT);
4136 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
4137 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004138 mWindow1->setTouchModal(false);
4139 mWindow1->setSplitTouch(true);
chaviwaf87b3e2019-10-01 16:59:28 -07004140 mWindow1->setFrame(Rect(0, 0, 100, 100));
4141
4142 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4143 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004144 mWindow2->setTouchModal(false);
4145 mWindow2->setSplitTouch(true);
chaviwaf87b3e2019-10-01 16:59:28 -07004146 mWindow2->setFrame(Rect(100, 100, 200, 200));
4147
Arthur Hung72d8dc32020-03-28 00:48:39 +00004148 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004149 }
4150
4151protected:
4152 sp<FakeWindowHandle> mWindow1;
4153 sp<FakeWindowHandle> mWindow2;
4154
4155 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004156 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004157 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4158 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004159 }
4160
4161 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4162 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004163 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004164 InputEvent* event = window->consume();
4165
4166 ASSERT_NE(nullptr, event) << name.c_str()
4167 << ": consumer should have returned non-NULL event.";
4168
4169 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4170 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4171 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4172
4173 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004174 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004175
4176 for (size_t i = 0; i < points.size(); i++) {
4177 float expectedX = points[i].x;
4178 float expectedY = points[i].y;
4179
4180 EXPECT_EQ(expectedX, motionEvent.getX(i))
4181 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4182 << ", got " << motionEvent.getX(i);
4183 EXPECT_EQ(expectedY, motionEvent.getY(i))
4184 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4185 << ", got " << motionEvent.getY(i);
4186 }
4187 }
chaviw9eaa22c2020-07-01 16:21:27 -07004188
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004189 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004190 std::vector<PointF> expectedPoints) {
4191 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4192 ADISPLAY_ID_DEFAULT, touchedPoints);
4193 mDispatcher->notifyMotion(&motionArgs);
4194
4195 // Always consume from window1 since it's the window that has the InputReceiver
4196 consumeMotionEvent(mWindow1, action, expectedPoints);
4197 }
chaviwaf87b3e2019-10-01 16:59:28 -07004198};
4199
4200TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4201 // Touch Window 1
4202 PointF touchedPoint = {10, 10};
4203 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004204 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004205
4206 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004207 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004208
4209 // Touch Window 2
4210 touchedPoint = {150, 150};
4211 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004212 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004213}
4214
chaviw9eaa22c2020-07-01 16:21:27 -07004215TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4216 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004217 mWindow2->setWindowScale(0.5f, 0.5f);
4218
4219 // Touch Window 1
4220 PointF touchedPoint = {10, 10};
4221 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004222 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004223 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004224 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004225
4226 // Touch Window 2
4227 touchedPoint = {150, 150};
4228 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004229 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4230 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004231
chaviw9eaa22c2020-07-01 16:21:27 -07004232 // Update the transform so rotation is set
4233 mWindow2->setWindowTransform(0, -1, 1, 0);
4234 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4235 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004236}
4237
chaviw9eaa22c2020-07-01 16:21:27 -07004238TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004239 mWindow2->setWindowScale(0.5f, 0.5f);
4240
4241 // Touch Window 1
4242 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4243 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004244 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004245
4246 // Touch Window 2
4247 int32_t actionPointerDown =
4248 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004249 touchedPoints.push_back(PointF{150, 150});
4250 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4251 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004252
chaviw9eaa22c2020-07-01 16:21:27 -07004253 // Release Window 2
4254 int32_t actionPointerUp =
4255 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4256 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4257 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004258
chaviw9eaa22c2020-07-01 16:21:27 -07004259 // Update the transform so rotation is set for Window 2
4260 mWindow2->setWindowTransform(0, -1, 1, 0);
4261 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4262 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004263}
4264
chaviw9eaa22c2020-07-01 16:21:27 -07004265TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004266 mWindow2->setWindowScale(0.5f, 0.5f);
4267
4268 // Touch Window 1
4269 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4270 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004271 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004272
4273 // Touch Window 2
4274 int32_t actionPointerDown =
4275 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004276 touchedPoints.push_back(PointF{150, 150});
4277 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004278
chaviw9eaa22c2020-07-01 16:21:27 -07004279 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004280
4281 // Move both windows
4282 touchedPoints = {{20, 20}, {175, 175}};
4283 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4284 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4285
chaviw9eaa22c2020-07-01 16:21:27 -07004286 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004287
chaviw9eaa22c2020-07-01 16:21:27 -07004288 // Release Window 2
4289 int32_t actionPointerUp =
4290 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4291 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4292 expectedPoints.pop_back();
4293
4294 // Touch Window 2
4295 mWindow2->setWindowTransform(0, -1, 1, 0);
4296 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4297 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4298
4299 // Move both windows
4300 touchedPoints = {{20, 20}, {175, 175}};
4301 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4302 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4303
4304 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004305}
4306
4307TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4308 mWindow1->setWindowScale(0.5f, 0.5f);
4309
4310 // Touch Window 1
4311 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4312 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004313 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004314
4315 // Touch Window 2
4316 int32_t actionPointerDown =
4317 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004318 touchedPoints.push_back(PointF{150, 150});
4319 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004320
chaviw9eaa22c2020-07-01 16:21:27 -07004321 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004322
4323 // Move both windows
4324 touchedPoints = {{20, 20}, {175, 175}};
4325 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4326 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4327
chaviw9eaa22c2020-07-01 16:21:27 -07004328 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004329}
4330
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004331class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4332 virtual void SetUp() override {
4333 InputDispatcherTest::SetUp();
4334
Chris Yea209fde2020-07-22 13:54:51 -07004335 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004336 mApplication->setDispatchingTimeout(20ms);
4337 mWindow =
4338 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4339 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004340 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004341 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004342 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4343 // window.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004344 mWindow->setTouchModal(false);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004345
4346 // Set focused application.
4347 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4348
4349 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004350 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004351 mWindow->consumeFocusEvent(true);
4352 }
4353
4354 virtual void TearDown() override {
4355 InputDispatcherTest::TearDown();
4356 mWindow.clear();
4357 }
4358
4359protected:
Chris Yea209fde2020-07-22 13:54:51 -07004360 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004361 sp<FakeWindowHandle> mWindow;
4362 static constexpr PointF WINDOW_LOCATION = {20, 20};
4363
4364 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004365 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004366 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4367 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004368 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004369 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4370 WINDOW_LOCATION));
4371 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004372
4373 sp<FakeWindowHandle> addSpyWindow() {
4374 sp<FakeWindowHandle> spy =
4375 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4376 spy->setTrustedOverlay(true);
4377 spy->setFocusable(false);
4378 spy->setInputFeatures(WindowInfo::Feature::SPY);
4379 spy->setDispatchingTimeout(30ms);
4380 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4381 return spy;
4382 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004383};
4384
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004385// Send a tap and respond, which should not cause an ANR.
4386TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4387 tapOnWindow();
4388 mWindow->consumeMotionDown();
4389 mWindow->consumeMotionUp();
4390 ASSERT_TRUE(mDispatcher->waitForIdle());
4391 mFakePolicy->assertNotifyAnrWasNotCalled();
4392}
4393
4394// Send a regular key and respond, which should not cause an ANR.
4395TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004396 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004397 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4398 ASSERT_TRUE(mDispatcher->waitForIdle());
4399 mFakePolicy->assertNotifyAnrWasNotCalled();
4400}
4401
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004402TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4403 mWindow->setFocusable(false);
4404 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4405 mWindow->consumeFocusEvent(false);
4406
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004407 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004408 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004409 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4410 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004411 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004412 // Key will not go to window because we have no focused window.
4413 // The 'no focused window' ANR timer should start instead.
4414
4415 // Now, the focused application goes away.
4416 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4417 // The key should get dropped and there should be no ANR.
4418
4419 ASSERT_TRUE(mDispatcher->waitForIdle());
4420 mFakePolicy->assertNotifyAnrWasNotCalled();
4421}
4422
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004423// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004424// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4425// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004426TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004427 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004428 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4429 WINDOW_LOCATION));
4430
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004431 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4432 ASSERT_TRUE(sequenceNum);
4433 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004434 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004435
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004436 mWindow->finishEvent(*sequenceNum);
4437 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4438 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004439 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004440 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004441}
4442
4443// Send a key to the app and have the app not respond right away.
4444TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4445 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004446 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004447 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4448 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004449 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004450 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004451 ASSERT_TRUE(mDispatcher->waitForIdle());
4452}
4453
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004454// We have a focused application, but no focused window
4455TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004456 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004457 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4458 mWindow->consumeFocusEvent(false);
4459
4460 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004461 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004462 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4463 WINDOW_LOCATION));
4464 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4465 mDispatcher->waitForIdle();
4466 mFakePolicy->assertNotifyAnrWasNotCalled();
4467
4468 // Once a focused event arrives, we get an ANR for this application
4469 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4470 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004471 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004472 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004473 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004474 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004475 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004476 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004477 ASSERT_TRUE(mDispatcher->waitForIdle());
4478}
4479
4480// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004481// Make sure that we don't notify policy twice about the same ANR.
4482TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004483 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004484 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4485 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004486
4487 // Once a focused event arrives, we get an ANR for this application
4488 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4489 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004490 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004491 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004492 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004493 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004494 const std::chrono::duration appTimeout =
4495 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004496 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004497
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004498 std::this_thread::sleep_for(appTimeout);
4499 // ANR should not be raised again. It is up to policy to do that if it desires.
4500 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004501
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004502 // If we now get a focused window, the ANR should stop, but the policy handles that via
4503 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004504 ASSERT_TRUE(mDispatcher->waitForIdle());
4505}
4506
4507// We have a focused application, but no focused window
4508TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004509 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004510 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4511 mWindow->consumeFocusEvent(false);
4512
4513 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004514 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004515 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004516 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4517 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004518
4519 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004520 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004521
4522 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004523 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004524 ASSERT_TRUE(mDispatcher->waitForIdle());
4525 mWindow->assertNoEvents();
4526}
4527
4528/**
4529 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4530 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4531 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4532 * the ANR mechanism should still work.
4533 *
4534 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4535 * DOWN event, while not responding on the second one.
4536 */
4537TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4538 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4539 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4540 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4541 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4542 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004543 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004544
4545 // Now send ACTION_UP, with identical timestamp
4546 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4547 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4548 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4549 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004550 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004551
4552 // We have now sent down and up. Let's consume first event and then ANR on the second.
4553 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4554 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004555 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004556}
4557
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004558// A spy window can receive an ANR
4559TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4560 sp<FakeWindowHandle> spy = addSpyWindow();
4561
4562 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4563 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4564 WINDOW_LOCATION));
4565 mWindow->consumeMotionDown();
4566
4567 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4568 ASSERT_TRUE(sequenceNum);
4569 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4570 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy->getToken());
4571
4572 spy->finishEvent(*sequenceNum);
4573 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4574 0 /*flags*/);
4575 ASSERT_TRUE(mDispatcher->waitForIdle());
4576 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken());
4577}
4578
4579// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004580// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004581TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4582 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004583
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004584 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4585 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004586 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004587 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004588
4589 // Stuck on the ACTION_UP
4590 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004591 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004592
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004593 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004594 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004595 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4596 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004597
4598 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4599 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004600 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004601 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004602 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004603}
4604
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004605// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004606// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004607TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4608 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004609
4610 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004611 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4612 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004613
4614 mWindow->consumeMotionDown();
4615 // Stuck on the ACTION_UP
4616 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004617 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004618
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004619 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004620 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004621 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4622 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004623
4624 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4625 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004626 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004627 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004628 spy->assertNoEvents();
4629}
4630
4631TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4632 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4633
4634 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4635
4636 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4637 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4638 WINDOW_LOCATION));
4639
4640 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4641 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4642 ASSERT_TRUE(consumeSeq);
4643
4644 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(30ms);
4645
4646 monitor.finishEvent(*consumeSeq);
4647 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4648
4649 ASSERT_TRUE(mDispatcher->waitForIdle());
4650 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004651}
4652
4653// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4654// process events, you don't get an anr. When the window later becomes unresponsive again, you
4655// get an ANR again.
4656// 1. tap -> block on ACTION_UP -> receive ANR
4657// 2. consume all pending events (= queue becomes healthy again)
4658// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4659TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4660 tapOnWindow();
4661
4662 mWindow->consumeMotionDown();
4663 // Block on ACTION_UP
4664 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004665 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004666 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4667 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004668 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004669 mWindow->assertNoEvents();
4670
4671 tapOnWindow();
4672 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004673 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004674 mWindow->consumeMotionUp();
4675
4676 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004677 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004678 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004679 mWindow->assertNoEvents();
4680}
4681
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004682// If a connection remains unresponsive for a while, make sure policy is only notified once about
4683// it.
4684TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004685 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004686 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4687 WINDOW_LOCATION));
4688
4689 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004690 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004691 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004692 // 'notifyConnectionUnresponsive' should only be called once per connection
4693 mFakePolicy->assertNotifyAnrWasNotCalled();
4694 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004695 mWindow->consumeMotionDown();
4696 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4697 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4698 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004699 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004700 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004701 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004702}
4703
4704/**
4705 * If a window is processing a motion event, and then a key event comes in, the key event should
4706 * not to to the focused window until the motion is processed.
4707 *
4708 * Warning!!!
4709 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4710 * and the injection timeout that we specify when injecting the key.
4711 * We must have the injection timeout (10ms) be smaller than
4712 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4713 *
4714 * If that value changes, this test should also change.
4715 */
4716TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4717 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4718 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4719
4720 tapOnWindow();
4721 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4722 ASSERT_TRUE(downSequenceNum);
4723 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4724 ASSERT_TRUE(upSequenceNum);
4725 // Don't finish the events yet, and send a key
4726 // Injection will "succeed" because we will eventually give up and send the key to the focused
4727 // window even if motions are still being processed. But because the injection timeout is short,
4728 // we will receive INJECTION_TIMED_OUT as the result.
4729
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004730 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004731 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004732 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4733 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004734 // Key will not be sent to the window, yet, because the window is still processing events
4735 // and the key remains pending, waiting for the touch events to be processed
4736 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4737 ASSERT_FALSE(keySequenceNum);
4738
4739 std::this_thread::sleep_for(500ms);
4740 // if we wait long enough though, dispatcher will give up, and still send the key
4741 // to the focused window, even though we have not yet finished the motion event
4742 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4743 mWindow->finishEvent(*downSequenceNum);
4744 mWindow->finishEvent(*upSequenceNum);
4745}
4746
4747/**
4748 * If a window is processing a motion event, and then a key event comes in, the key event should
4749 * not go to the focused window until the motion is processed.
4750 * If then a new motion comes in, then the pending key event should be going to the currently
4751 * focused window right away.
4752 */
4753TEST_F(InputDispatcherSingleWindowAnr,
4754 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4755 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4756 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4757
4758 tapOnWindow();
4759 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4760 ASSERT_TRUE(downSequenceNum);
4761 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4762 ASSERT_TRUE(upSequenceNum);
4763 // Don't finish the events yet, and send a key
4764 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004765 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004766 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004767 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004768 // At this point, key is still pending, and should not be sent to the application yet.
4769 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4770 ASSERT_FALSE(keySequenceNum);
4771
4772 // Now tap down again. It should cause the pending key to go to the focused window right away.
4773 tapOnWindow();
4774 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4775 // the other events yet. We can finish events in any order.
4776 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4777 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4778 mWindow->consumeMotionDown();
4779 mWindow->consumeMotionUp();
4780 mWindow->assertNoEvents();
4781}
4782
4783class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4784 virtual void SetUp() override {
4785 InputDispatcherTest::SetUp();
4786
Chris Yea209fde2020-07-22 13:54:51 -07004787 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004788 mApplication->setDispatchingTimeout(10ms);
4789 mUnfocusedWindow =
4790 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4791 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4792 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4793 // window.
4794 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004795 mUnfocusedWindow->setTouchModal(false);
4796 mUnfocusedWindow->setSplitTouch(true);
4797 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004798
4799 mFocusedWindow =
4800 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004801 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004802 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004803 mFocusedWindow->setTouchModal(false);
4804 mFocusedWindow->setSplitTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004805
4806 // Set focused application.
4807 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004808 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004809
4810 // Expect one focus window exist in display.
4811 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004812 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004813 mFocusedWindow->consumeFocusEvent(true);
4814 }
4815
4816 virtual void TearDown() override {
4817 InputDispatcherTest::TearDown();
4818
4819 mUnfocusedWindow.clear();
4820 mFocusedWindow.clear();
4821 }
4822
4823protected:
Chris Yea209fde2020-07-22 13:54:51 -07004824 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004825 sp<FakeWindowHandle> mUnfocusedWindow;
4826 sp<FakeWindowHandle> mFocusedWindow;
4827 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4828 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4829 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4830
4831 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4832
4833 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4834
4835private:
4836 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004837 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004838 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4839 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004840 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004841 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4842 location));
4843 }
4844};
4845
4846// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4847// should be ANR'd first.
4848TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004849 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004850 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4851 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004852 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004853 mFocusedWindow->consumeMotionDown();
4854 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4855 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4856 // We consumed all events, so no ANR
4857 ASSERT_TRUE(mDispatcher->waitForIdle());
4858 mFakePolicy->assertNotifyAnrWasNotCalled();
4859
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004860 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004861 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4862 FOCUSED_WINDOW_LOCATION));
4863 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4864 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004865
4866 const std::chrono::duration timeout =
4867 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004868 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004869 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4870 // sequence to make it consistent
4871 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004872 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004873 mFocusedWindow->consumeMotionDown();
4874 // This cancel is generated because the connection was unresponsive
4875 mFocusedWindow->consumeMotionCancel();
4876 mFocusedWindow->assertNoEvents();
4877 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004878 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004879 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004880 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004881}
4882
4883// If we have 2 windows with identical timeouts that are both unresponsive,
4884// it doesn't matter which order they should have ANR.
4885// But we should receive ANR for both.
4886TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4887 // Set the timeout for unfocused window to match the focused window
4888 mUnfocusedWindow->setDispatchingTimeout(10ms);
4889 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4890
4891 tapOnFocusedWindow();
4892 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004893 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4894 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004895
4896 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004897 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4898 mFocusedWindow->getToken() == anrConnectionToken2);
4899 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4900 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004901
4902 ASSERT_TRUE(mDispatcher->waitForIdle());
4903 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004904
4905 mFocusedWindow->consumeMotionDown();
4906 mFocusedWindow->consumeMotionUp();
4907 mUnfocusedWindow->consumeMotionOutside();
4908
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004909 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4910 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004911
4912 // Both applications should be marked as responsive, in any order
4913 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4914 mFocusedWindow->getToken() == responsiveToken2);
4915 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4916 mUnfocusedWindow->getToken() == responsiveToken2);
4917 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004918}
4919
4920// If a window is already not responding, the second tap on the same window should be ignored.
4921// We should also log an error to account for the dropped event (not tested here).
4922// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4923TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4924 tapOnFocusedWindow();
4925 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4926 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4927 // Receive the events, but don't respond
4928 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4929 ASSERT_TRUE(downEventSequenceNum);
4930 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4931 ASSERT_TRUE(upEventSequenceNum);
4932 const std::chrono::duration timeout =
4933 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004934 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004935
4936 // Tap once again
4937 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004938 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004939 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4940 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004941 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004942 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4943 FOCUSED_WINDOW_LOCATION));
4944 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4945 // valid touch target
4946 mUnfocusedWindow->assertNoEvents();
4947
4948 // Consume the first tap
4949 mFocusedWindow->finishEvent(*downEventSequenceNum);
4950 mFocusedWindow->finishEvent(*upEventSequenceNum);
4951 ASSERT_TRUE(mDispatcher->waitForIdle());
4952 // The second tap did not go to the focused window
4953 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004954 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004955 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004956 mFakePolicy->assertNotifyAnrWasNotCalled();
4957}
4958
4959// If you tap outside of all windows, there will not be ANR
4960TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004961 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004962 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4963 LOCATION_OUTSIDE_ALL_WINDOWS));
4964 ASSERT_TRUE(mDispatcher->waitForIdle());
4965 mFakePolicy->assertNotifyAnrWasNotCalled();
4966}
4967
4968// Since the focused window is paused, tapping on it should not produce any events
4969TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4970 mFocusedWindow->setPaused(true);
4971 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4972
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004973 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004974 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4975 FOCUSED_WINDOW_LOCATION));
4976
4977 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4978 ASSERT_TRUE(mDispatcher->waitForIdle());
4979 // Should not ANR because the window is paused, and touches shouldn't go to it
4980 mFakePolicy->assertNotifyAnrWasNotCalled();
4981
4982 mFocusedWindow->assertNoEvents();
4983 mUnfocusedWindow->assertNoEvents();
4984}
4985
4986/**
4987 * If a window is processing a motion event, and then a key event comes in, the key event should
4988 * not to to the focused window until the motion is processed.
4989 * If a different window becomes focused at this time, the key should go to that window instead.
4990 *
4991 * Warning!!!
4992 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4993 * and the injection timeout that we specify when injecting the key.
4994 * We must have the injection timeout (10ms) be smaller than
4995 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4996 *
4997 * If that value changes, this test should also change.
4998 */
4999TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5000 // Set a long ANR timeout to prevent it from triggering
5001 mFocusedWindow->setDispatchingTimeout(2s);
5002 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5003
5004 tapOnUnfocusedWindow();
5005 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5006 ASSERT_TRUE(downSequenceNum);
5007 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5008 ASSERT_TRUE(upSequenceNum);
5009 // Don't finish the events yet, and send a key
5010 // Injection will succeed because we will eventually give up and send the key to the focused
5011 // window even if motions are still being processed.
5012
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005013 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005014 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005015 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5016 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005017 // Key will not be sent to the window, yet, because the window is still processing events
5018 // and the key remains pending, waiting for the touch events to be processed
5019 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5020 ASSERT_FALSE(keySequenceNum);
5021
5022 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005023 mFocusedWindow->setFocusable(false);
5024 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005025 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005026 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005027
5028 // Focus events should precede the key events
5029 mUnfocusedWindow->consumeFocusEvent(true);
5030 mFocusedWindow->consumeFocusEvent(false);
5031
5032 // Finish the tap events, which should unblock dispatcher
5033 mUnfocusedWindow->finishEvent(*downSequenceNum);
5034 mUnfocusedWindow->finishEvent(*upSequenceNum);
5035
5036 // Now that all queues are cleared and no backlog in the connections, the key event
5037 // can finally go to the newly focused "mUnfocusedWindow".
5038 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5039 mFocusedWindow->assertNoEvents();
5040 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005041 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005042}
5043
5044// When the touch stream is split across 2 windows, and one of them does not respond,
5045// then ANR should be raised and the touch should be canceled for the unresponsive window.
5046// The other window should not be affected by that.
5047TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5048 // Touch Window 1
5049 NotifyMotionArgs motionArgs =
5050 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5051 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5052 mDispatcher->notifyMotion(&motionArgs);
5053 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5054 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5055
5056 // Touch Window 2
5057 int32_t actionPointerDown =
5058 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
5059
5060 motionArgs =
5061 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5062 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
5063 mDispatcher->notifyMotion(&motionArgs);
5064
5065 const std::chrono::duration timeout =
5066 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005067 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005068
5069 mUnfocusedWindow->consumeMotionDown();
5070 mFocusedWindow->consumeMotionDown();
5071 // Focused window may or may not receive ACTION_MOVE
5072 // But it should definitely receive ACTION_CANCEL due to the ANR
5073 InputEvent* event;
5074 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5075 ASSERT_TRUE(moveOrCancelSequenceNum);
5076 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5077 ASSERT_NE(nullptr, event);
5078 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5079 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5080 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5081 mFocusedWindow->consumeMotionCancel();
5082 } else {
5083 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5084 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005085 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005086 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005087
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005088 mUnfocusedWindow->assertNoEvents();
5089 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005090 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005091}
5092
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005093/**
5094 * If we have no focused window, and a key comes in, we start the ANR timer.
5095 * The focused application should add a focused window before the timer runs out to prevent ANR.
5096 *
5097 * If the user touches another application during this time, the key should be dropped.
5098 * Next, if a new focused window comes in, without toggling the focused application,
5099 * then no ANR should occur.
5100 *
5101 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5102 * but in some cases the policy may not update the focused application.
5103 */
5104TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5105 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5106 std::make_shared<FakeApplicationHandle>();
5107 focusedApplication->setDispatchingTimeout(60ms);
5108 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5109 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5110 mFocusedWindow->setFocusable(false);
5111
5112 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5113 mFocusedWindow->consumeFocusEvent(false);
5114
5115 // Send a key. The ANR timer should start because there is no focused window.
5116 // 'focusedApplication' will get blamed if this timer completes.
5117 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005118 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005119 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005120 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5121 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005122 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005123
5124 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5125 // then the injected touches won't cause the focused event to get dropped.
5126 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5127 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5128 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5129 // For this test, it means that the key would get delivered to the window once it becomes
5130 // focused.
5131 std::this_thread::sleep_for(10ms);
5132
5133 // Touch unfocused window. This should force the pending key to get dropped.
5134 NotifyMotionArgs motionArgs =
5135 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5136 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5137 mDispatcher->notifyMotion(&motionArgs);
5138
5139 // We do not consume the motion right away, because that would require dispatcher to first
5140 // process (== drop) the key event, and by that time, ANR will be raised.
5141 // Set the focused window first.
5142 mFocusedWindow->setFocusable(true);
5143 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5144 setFocusedWindow(mFocusedWindow);
5145 mFocusedWindow->consumeFocusEvent(true);
5146 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5147 // to another application. This could be a bug / behaviour in the policy.
5148
5149 mUnfocusedWindow->consumeMotionDown();
5150
5151 ASSERT_TRUE(mDispatcher->waitForIdle());
5152 // Should not ANR because we actually have a focused window. It was just added too slowly.
5153 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5154}
5155
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005156// These tests ensure we cannot send touch events to a window that's positioned behind a window
5157// that has feature NO_INPUT_CHANNEL.
5158// Layout:
5159// Top (closest to user)
5160// mNoInputWindow (above all windows)
5161// mBottomWindow
5162// Bottom (furthest from user)
5163class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5164 virtual void SetUp() override {
5165 InputDispatcherTest::SetUp();
5166
5167 mApplication = std::make_shared<FakeApplicationHandle>();
5168 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5169 "Window without input channel", ADISPLAY_ID_DEFAULT,
5170 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5171
chaviw3277faf2021-05-19 16:45:23 -05005172 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005173 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5174 // It's perfectly valid for this window to not have an associated input channel
5175
5176 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5177 ADISPLAY_ID_DEFAULT);
5178 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5179
5180 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5181 }
5182
5183protected:
5184 std::shared_ptr<FakeApplicationHandle> mApplication;
5185 sp<FakeWindowHandle> mNoInputWindow;
5186 sp<FakeWindowHandle> mBottomWindow;
5187};
5188
5189TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5190 PointF touchedPoint = {10, 10};
5191
5192 NotifyMotionArgs motionArgs =
5193 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5194 ADISPLAY_ID_DEFAULT, {touchedPoint});
5195 mDispatcher->notifyMotion(&motionArgs);
5196
5197 mNoInputWindow->assertNoEvents();
5198 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5199 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5200 // and therefore should prevent mBottomWindow from receiving touches
5201 mBottomWindow->assertNoEvents();
5202}
5203
5204/**
5205 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5206 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5207 */
5208TEST_F(InputDispatcherMultiWindowOcclusionTests,
5209 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5210 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5211 "Window with input channel and NO_INPUT_CHANNEL",
5212 ADISPLAY_ID_DEFAULT);
5213
chaviw3277faf2021-05-19 16:45:23 -05005214 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005215 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5216 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5217
5218 PointF touchedPoint = {10, 10};
5219
5220 NotifyMotionArgs motionArgs =
5221 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5222 ADISPLAY_ID_DEFAULT, {touchedPoint});
5223 mDispatcher->notifyMotion(&motionArgs);
5224
5225 mNoInputWindow->assertNoEvents();
5226 mBottomWindow->assertNoEvents();
5227}
5228
Vishnu Nair958da932020-08-21 17:12:37 -07005229class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5230protected:
5231 std::shared_ptr<FakeApplicationHandle> mApp;
5232 sp<FakeWindowHandle> mWindow;
5233 sp<FakeWindowHandle> mMirror;
5234
5235 virtual void SetUp() override {
5236 InputDispatcherTest::SetUp();
5237 mApp = std::make_shared<FakeApplicationHandle>();
5238 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5239 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5240 mWindow->getToken());
5241 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5242 mWindow->setFocusable(true);
5243 mMirror->setFocusable(true);
5244 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5245 }
5246};
5247
5248TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5249 // Request focus on a mirrored window
5250 setFocusedWindow(mMirror);
5251
5252 // window gets focused
5253 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005254 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5255 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005256 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5257}
5258
5259// A focused & mirrored window remains focused only if the window and its mirror are both
5260// focusable.
5261TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5262 setFocusedWindow(mMirror);
5263
5264 // window gets focused
5265 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005266 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5267 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005268 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005269 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5270 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005271 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5272
5273 mMirror->setFocusable(false);
5274 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5275
5276 // window loses focus since one of the windows associated with the token in not focusable
5277 mWindow->consumeFocusEvent(false);
5278
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005279 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5280 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005281 mWindow->assertNoEvents();
5282}
5283
5284// A focused & mirrored window remains focused until the window and its mirror both become
5285// invisible.
5286TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5287 setFocusedWindow(mMirror);
5288
5289 // window gets focused
5290 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005291 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5292 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005293 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005294 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5295 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005296 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5297
5298 mMirror->setVisible(false);
5299 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5300
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005301 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5302 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005303 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005304 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5305 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005306 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5307
5308 mWindow->setVisible(false);
5309 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5310
5311 // window loses focus only after all windows associated with the token become invisible.
5312 mWindow->consumeFocusEvent(false);
5313
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005314 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5315 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005316 mWindow->assertNoEvents();
5317}
5318
5319// A focused & mirrored window remains focused until both windows are removed.
5320TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5321 setFocusedWindow(mMirror);
5322
5323 // window gets focused
5324 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005325 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5326 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005327 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005328 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5329 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005330 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5331
5332 // single window is removed but the window token remains focused
5333 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5334
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005335 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5336 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005337 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005338 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5339 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005340 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5341
5342 // Both windows are removed
5343 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5344 mWindow->consumeFocusEvent(false);
5345
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005346 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5347 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005348 mWindow->assertNoEvents();
5349}
5350
5351// Focus request can be pending until one window becomes visible.
5352TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5353 // Request focus on an invisible mirror.
5354 mWindow->setVisible(false);
5355 mMirror->setVisible(false);
5356 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5357 setFocusedWindow(mMirror);
5358
5359 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005360 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005361 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005362 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005363
5364 mMirror->setVisible(true);
5365 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5366
5367 // window gets focused
5368 mWindow->consumeFocusEvent(true);
5369 // window gets the pending key event
5370 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5371}
Prabir Pradhan99987712020-11-10 18:43:05 -08005372
5373class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5374protected:
5375 std::shared_ptr<FakeApplicationHandle> mApp;
5376 sp<FakeWindowHandle> mWindow;
5377 sp<FakeWindowHandle> mSecondWindow;
5378
5379 void SetUp() override {
5380 InputDispatcherTest::SetUp();
5381 mApp = std::make_shared<FakeApplicationHandle>();
5382 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5383 mWindow->setFocusable(true);
5384 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5385 mSecondWindow->setFocusable(true);
5386
5387 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5388 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5389
5390 setFocusedWindow(mWindow);
5391 mWindow->consumeFocusEvent(true);
5392 }
5393
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005394 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5395 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005396 mDispatcher->notifyPointerCaptureChanged(&args);
5397 }
5398
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005399 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5400 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005401 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005402 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5403 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005404 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005405 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005406 }
5407};
5408
5409TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5410 // Ensure that capture cannot be obtained for unfocused windows.
5411 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5412 mFakePolicy->assertSetPointerCaptureNotCalled();
5413 mSecondWindow->assertNoEvents();
5414
5415 // Ensure that capture can be enabled from the focus window.
5416 requestAndVerifyPointerCapture(mWindow, true);
5417
5418 // Ensure that capture cannot be disabled from a window that does not have capture.
5419 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5420 mFakePolicy->assertSetPointerCaptureNotCalled();
5421
5422 // Ensure that capture can be disabled from the window with capture.
5423 requestAndVerifyPointerCapture(mWindow, false);
5424}
5425
5426TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005427 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005428
5429 setFocusedWindow(mSecondWindow);
5430
5431 // Ensure that the capture disabled event was sent first.
5432 mWindow->consumeCaptureEvent(false);
5433 mWindow->consumeFocusEvent(false);
5434 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005435 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005436
5437 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005438 notifyPointerCaptureChanged({});
5439 notifyPointerCaptureChanged(request);
5440 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005441 mWindow->assertNoEvents();
5442 mSecondWindow->assertNoEvents();
5443 mFakePolicy->assertSetPointerCaptureNotCalled();
5444}
5445
5446TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005447 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005448
5449 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005450 notifyPointerCaptureChanged({});
5451 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005452
5453 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005454 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005455 mWindow->consumeCaptureEvent(false);
5456 mWindow->assertNoEvents();
5457}
5458
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005459TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5460 requestAndVerifyPointerCapture(mWindow, true);
5461
5462 // The first window loses focus.
5463 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005464 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005465 mWindow->consumeCaptureEvent(false);
5466
5467 // Request Pointer Capture from the second window before the notification from InputReader
5468 // arrives.
5469 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005470 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005471
5472 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005473 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005474
5475 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005476 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005477
5478 mSecondWindow->consumeFocusEvent(true);
5479 mSecondWindow->consumeCaptureEvent(true);
5480}
5481
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005482TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5483 // App repeatedly enables and disables capture.
5484 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5485 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5486 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5487 mFakePolicy->assertSetPointerCaptureCalled(false);
5488 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5489 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5490
5491 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5492 // first request is now stale, this should do nothing.
5493 notifyPointerCaptureChanged(firstRequest);
5494 mWindow->assertNoEvents();
5495
5496 // InputReader notifies that the second request was enabled.
5497 notifyPointerCaptureChanged(secondRequest);
5498 mWindow->consumeCaptureEvent(true);
5499}
5500
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005501class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5502protected:
5503 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005504
5505 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5506 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5507
5508 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5509 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5510
5511 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5512 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5513 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5514 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5515 MAXIMUM_OBSCURING_OPACITY);
5516
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005517 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005518 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005519 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005520
5521 sp<FakeWindowHandle> mTouchWindow;
5522
5523 virtual void SetUp() override {
5524 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005525 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005526 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5527 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5528 }
5529
5530 virtual void TearDown() override {
5531 InputDispatcherTest::TearDown();
5532 mTouchWindow.clear();
5533 }
5534
chaviw3277faf2021-05-19 16:45:23 -05005535 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5536 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005537 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005538 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005539 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005540 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005541 return window;
5542 }
5543
5544 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5545 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5546 sp<FakeWindowHandle> window =
5547 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5548 // Generate an arbitrary PID based on the UID
5549 window->setOwnerInfo(1777 + (uid % 10000), uid);
5550 return window;
5551 }
5552
5553 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5554 NotifyMotionArgs args =
5555 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5556 ADISPLAY_ID_DEFAULT, points);
5557 mDispatcher->notifyMotion(&args);
5558 }
5559};
5560
5561TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005562 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005563 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005564 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005565
5566 touch();
5567
5568 mTouchWindow->assertNoEvents();
5569}
5570
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005571TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005572 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5573 const sp<FakeWindowHandle>& w =
5574 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5575 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5576
5577 touch();
5578
5579 mTouchWindow->assertNoEvents();
5580}
5581
5582TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005583 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5584 const sp<FakeWindowHandle>& w =
5585 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5586 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5587
5588 touch();
5589
5590 w->assertNoEvents();
5591}
5592
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005593TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005594 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5595 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005596
5597 touch();
5598
5599 mTouchWindow->consumeAnyMotionDown();
5600}
5601
5602TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005603 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005604 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005605 w->setFrame(Rect(0, 0, 50, 50));
5606 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005607
5608 touch({PointF{100, 100}});
5609
5610 mTouchWindow->consumeAnyMotionDown();
5611}
5612
5613TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005614 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005615 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005616 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5617
5618 touch();
5619
5620 mTouchWindow->consumeAnyMotionDown();
5621}
5622
5623TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5624 const sp<FakeWindowHandle>& w =
5625 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5626 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005627
5628 touch();
5629
5630 mTouchWindow->consumeAnyMotionDown();
5631}
5632
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005633TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5634 const sp<FakeWindowHandle>& w =
5635 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5637
5638 touch();
5639
5640 w->assertNoEvents();
5641}
5642
5643/**
5644 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5645 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5646 * window, the occluding window will still receive ACTION_OUTSIDE event.
5647 */
5648TEST_F(InputDispatcherUntrustedTouchesTest,
5649 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5650 const sp<FakeWindowHandle>& w =
5651 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005652 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005653 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5654
5655 touch();
5656
5657 w->consumeMotionOutside();
5658}
5659
5660TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5661 const sp<FakeWindowHandle>& w =
5662 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005663 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005664 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5665
5666 touch();
5667
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005668 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005669}
5670
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005671TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005672 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005673 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5674 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005675 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5676
5677 touch();
5678
5679 mTouchWindow->consumeAnyMotionDown();
5680}
5681
5682TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5683 const sp<FakeWindowHandle>& w =
5684 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5685 MAXIMUM_OBSCURING_OPACITY);
5686 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005687
5688 touch();
5689
5690 mTouchWindow->consumeAnyMotionDown();
5691}
5692
5693TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005694 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005695 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5696 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005697 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5698
5699 touch();
5700
5701 mTouchWindow->assertNoEvents();
5702}
5703
5704TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5705 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5706 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005707 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5708 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005709 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005710 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5711 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005712 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5713
5714 touch();
5715
5716 mTouchWindow->assertNoEvents();
5717}
5718
5719TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5720 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5721 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005722 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5723 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005724 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005725 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5726 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005727 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5728
5729 touch();
5730
5731 mTouchWindow->consumeAnyMotionDown();
5732}
5733
5734TEST_F(InputDispatcherUntrustedTouchesTest,
5735 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5736 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005737 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5738 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005739 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005740 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5741 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005742 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5743
5744 touch();
5745
5746 mTouchWindow->consumeAnyMotionDown();
5747}
5748
5749TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5750 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005751 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5752 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005753 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005754 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5755 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005756 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005757
5758 touch();
5759
5760 mTouchWindow->assertNoEvents();
5761}
5762
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005763TEST_F(InputDispatcherUntrustedTouchesTest,
5764 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5765 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005766 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5767 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005768 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005769 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5770 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005771 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5772
5773 touch();
5774
5775 mTouchWindow->assertNoEvents();
5776}
5777
5778TEST_F(InputDispatcherUntrustedTouchesTest,
5779 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5780 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005781 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5782 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005783 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005784 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5785 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005786 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5787
5788 touch();
5789
5790 mTouchWindow->consumeAnyMotionDown();
5791}
5792
5793TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5794 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005795 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5796 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005797 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5798
5799 touch();
5800
5801 mTouchWindow->consumeAnyMotionDown();
5802}
5803
5804TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5805 const sp<FakeWindowHandle>& w =
5806 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5807 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5808
5809 touch();
5810
5811 mTouchWindow->consumeAnyMotionDown();
5812}
5813
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005814TEST_F(InputDispatcherUntrustedTouchesTest,
5815 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5816 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5817 const sp<FakeWindowHandle>& w =
5818 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5819 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5820
5821 touch();
5822
5823 mTouchWindow->assertNoEvents();
5824}
5825
5826TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5827 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5828 const sp<FakeWindowHandle>& w =
5829 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5830 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5831
5832 touch();
5833
5834 mTouchWindow->consumeAnyMotionDown();
5835}
5836
5837TEST_F(InputDispatcherUntrustedTouchesTest,
5838 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5839 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5840 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005841 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5842 OPACITY_ABOVE_THRESHOLD);
5843 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5844
5845 touch();
5846
5847 mTouchWindow->consumeAnyMotionDown();
5848}
5849
5850TEST_F(InputDispatcherUntrustedTouchesTest,
5851 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5852 const sp<FakeWindowHandle>& w1 =
5853 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5854 OPACITY_BELOW_THRESHOLD);
5855 const sp<FakeWindowHandle>& w2 =
5856 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5857 OPACITY_BELOW_THRESHOLD);
5858 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5859
5860 touch();
5861
5862 mTouchWindow->assertNoEvents();
5863}
5864
5865/**
5866 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5867 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5868 * (which alone would result in allowing touches) does not affect the blocking behavior.
5869 */
5870TEST_F(InputDispatcherUntrustedTouchesTest,
5871 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5872 const sp<FakeWindowHandle>& wB =
5873 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5874 OPACITY_BELOW_THRESHOLD);
5875 const sp<FakeWindowHandle>& wC =
5876 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5877 OPACITY_BELOW_THRESHOLD);
5878 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5879
5880 touch();
5881
5882 mTouchWindow->assertNoEvents();
5883}
5884
5885/**
5886 * This test is testing that a window from a different UID but with same application token doesn't
5887 * block the touch. Apps can share the application token for close UI collaboration for example.
5888 */
5889TEST_F(InputDispatcherUntrustedTouchesTest,
5890 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5891 const sp<FakeWindowHandle>& w =
5892 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5893 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005894 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5895
5896 touch();
5897
5898 mTouchWindow->consumeAnyMotionDown();
5899}
5900
arthurhungb89ccb02020-12-30 16:19:01 +08005901class InputDispatcherDragTests : public InputDispatcherTest {
5902protected:
5903 std::shared_ptr<FakeApplicationHandle> mApp;
5904 sp<FakeWindowHandle> mWindow;
5905 sp<FakeWindowHandle> mSecondWindow;
5906 sp<FakeWindowHandle> mDragWindow;
5907
5908 void SetUp() override {
5909 InputDispatcherTest::SetUp();
5910 mApp = std::make_shared<FakeApplicationHandle>();
5911 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5912 mWindow->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005913 mWindow->setTouchModal(false);
arthurhungb89ccb02020-12-30 16:19:01 +08005914
5915 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5916 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005917 mSecondWindow->setTouchModal(false);
arthurhungb89ccb02020-12-30 16:19:01 +08005918
5919 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5920 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5921 }
5922
5923 // Start performing drag, we will create a drag window and transfer touch to it.
5924 void performDrag() {
5925 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5926 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5927 {50, 50}))
5928 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5929
5930 // Window should receive motion event.
5931 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5932
5933 // The drag window covers the entire display
5934 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5935 mDispatcher->setInputWindows(
5936 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5937
5938 // Transfer touch focus to the drag window
5939 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5940 true /* isDragDrop */);
5941 mWindow->consumeMotionCancel();
5942 mDragWindow->consumeMotionDown();
5943 }
arthurhung6d4bed92021-03-17 11:59:33 +08005944
5945 // Start performing drag, we will create a drag window and transfer touch to it.
5946 void performStylusDrag() {
5947 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5948 injectMotionEvent(mDispatcher,
5949 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5950 AINPUT_SOURCE_STYLUS)
5951 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5952 .pointer(PointerBuilder(0,
5953 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5954 .x(50)
5955 .y(50))
5956 .build()));
5957 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5958
5959 // The drag window covers the entire display
5960 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5961 mDispatcher->setInputWindows(
5962 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5963
5964 // Transfer touch focus to the drag window
5965 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5966 true /* isDragDrop */);
5967 mWindow->consumeMotionCancel();
5968 mDragWindow->consumeMotionDown();
5969 }
arthurhungb89ccb02020-12-30 16:19:01 +08005970};
5971
5972TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5973 performDrag();
5974
5975 // Move on window.
5976 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5977 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5978 ADISPLAY_ID_DEFAULT, {50, 50}))
5979 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5980 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5981 mWindow->consumeDragEvent(false, 50, 50);
5982 mSecondWindow->assertNoEvents();
5983
5984 // Move to another window.
5985 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5986 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5987 ADISPLAY_ID_DEFAULT, {150, 50}))
5988 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5989 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5990 mWindow->consumeDragEvent(true, 150, 50);
5991 mSecondWindow->consumeDragEvent(false, 50, 50);
5992
5993 // Move back to original window.
5994 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5995 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5996 ADISPLAY_ID_DEFAULT, {50, 50}))
5997 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5998 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5999 mWindow->consumeDragEvent(false, 50, 50);
6000 mSecondWindow->consumeDragEvent(true, -50, 50);
6001
6002 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6003 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6004 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6005 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6006 mWindow->assertNoEvents();
6007 mSecondWindow->assertNoEvents();
6008}
6009
arthurhungf452d0b2021-01-06 00:19:52 +08006010TEST_F(InputDispatcherDragTests, DragAndDrop) {
6011 performDrag();
6012
6013 // Move on window.
6014 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6015 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6016 ADISPLAY_ID_DEFAULT, {50, 50}))
6017 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6018 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6019 mWindow->consumeDragEvent(false, 50, 50);
6020 mSecondWindow->assertNoEvents();
6021
6022 // Move to another window.
6023 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6024 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6025 ADISPLAY_ID_DEFAULT, {150, 50}))
6026 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6027 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6028 mWindow->consumeDragEvent(true, 150, 50);
6029 mSecondWindow->consumeDragEvent(false, 50, 50);
6030
6031 // drop to another window.
6032 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6033 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6034 {150, 50}))
6035 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6036 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6037 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6038 mWindow->assertNoEvents();
6039 mSecondWindow->assertNoEvents();
6040}
6041
arthurhung6d4bed92021-03-17 11:59:33 +08006042TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6043 performStylusDrag();
6044
6045 // Move on window and keep button pressed.
6046 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6047 injectMotionEvent(mDispatcher,
6048 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6049 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6050 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6051 .x(50)
6052 .y(50))
6053 .build()))
6054 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6055 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6056 mWindow->consumeDragEvent(false, 50, 50);
6057 mSecondWindow->assertNoEvents();
6058
6059 // Move to another window and release button, expect to drop item.
6060 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6061 injectMotionEvent(mDispatcher,
6062 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6063 .buttonState(0)
6064 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6065 .x(150)
6066 .y(50))
6067 .build()))
6068 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6069 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6070 mWindow->assertNoEvents();
6071 mSecondWindow->assertNoEvents();
6072 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6073
6074 // nothing to the window.
6075 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6076 injectMotionEvent(mDispatcher,
6077 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6078 .buttonState(0)
6079 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6080 .x(150)
6081 .y(50))
6082 .build()))
6083 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6084 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6085 mWindow->assertNoEvents();
6086 mSecondWindow->assertNoEvents();
6087}
6088
Arthur Hung6d0571e2021-04-09 20:18:16 +08006089TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6090 performDrag();
6091
6092 // Set second window invisible.
6093 mSecondWindow->setVisible(false);
6094 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6095
6096 // Move on window.
6097 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6098 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6099 ADISPLAY_ID_DEFAULT, {50, 50}))
6100 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6101 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6102 mWindow->consumeDragEvent(false, 50, 50);
6103 mSecondWindow->assertNoEvents();
6104
6105 // Move to another window.
6106 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6107 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6108 ADISPLAY_ID_DEFAULT, {150, 50}))
6109 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6110 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6111 mWindow->consumeDragEvent(true, 150, 50);
6112 mSecondWindow->assertNoEvents();
6113
6114 // drop to another window.
6115 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6116 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6117 {150, 50}))
6118 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6119 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6120 mFakePolicy->assertDropTargetEquals(nullptr);
6121 mWindow->assertNoEvents();
6122 mSecondWindow->assertNoEvents();
6123}
6124
Vishnu Nair062a8672021-09-03 16:07:44 -07006125class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6126
6127TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6128 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6129 sp<FakeWindowHandle> window =
6130 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6131 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
6132 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6133 window->setFocusable(true);
6134 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6135 setFocusedWindow(window);
6136 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6137
6138 // With the flag set, window should not get any input
6139 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6140 mDispatcher->notifyKey(&keyArgs);
6141 window->assertNoEvents();
6142
6143 NotifyMotionArgs motionArgs =
6144 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6145 ADISPLAY_ID_DEFAULT);
6146 mDispatcher->notifyMotion(&motionArgs);
6147 window->assertNoEvents();
6148
6149 // With the flag cleared, the window should get input
6150 window->setInputFeatures({});
6151 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6152
6153 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6154 mDispatcher->notifyKey(&keyArgs);
6155 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6156
6157 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6158 ADISPLAY_ID_DEFAULT);
6159 mDispatcher->notifyMotion(&motionArgs);
6160 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6161 window->assertNoEvents();
6162}
6163
6164TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6165 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6166 std::make_shared<FakeApplicationHandle>();
6167 sp<FakeWindowHandle> obscuringWindow =
6168 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6169 ADISPLAY_ID_DEFAULT);
6170 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6171 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006172 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006173 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6174 sp<FakeWindowHandle> window =
6175 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6176 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6177 window->setOwnerInfo(222, 222);
6178 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6179 window->setFocusable(true);
6180 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6181 setFocusedWindow(window);
6182 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6183
6184 // With the flag set, window should not get any input
6185 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6186 mDispatcher->notifyKey(&keyArgs);
6187 window->assertNoEvents();
6188
6189 NotifyMotionArgs motionArgs =
6190 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6191 ADISPLAY_ID_DEFAULT);
6192 mDispatcher->notifyMotion(&motionArgs);
6193 window->assertNoEvents();
6194
6195 // With the flag cleared, the window should get input
6196 window->setInputFeatures({});
6197 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6198
6199 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6200 mDispatcher->notifyKey(&keyArgs);
6201 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6202
6203 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6204 ADISPLAY_ID_DEFAULT);
6205 mDispatcher->notifyMotion(&motionArgs);
6206 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6207 window->assertNoEvents();
6208}
6209
6210TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6211 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6212 std::make_shared<FakeApplicationHandle>();
6213 sp<FakeWindowHandle> obscuringWindow =
6214 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6215 ADISPLAY_ID_DEFAULT);
6216 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6217 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006218 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006219 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6220 sp<FakeWindowHandle> window =
6221 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6222 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6223 window->setOwnerInfo(222, 222);
6224 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6225 window->setFocusable(true);
6226 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6227 setFocusedWindow(window);
6228 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6229
6230 // With the flag set, window should not get any input
6231 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6232 mDispatcher->notifyKey(&keyArgs);
6233 window->assertNoEvents();
6234
6235 NotifyMotionArgs motionArgs =
6236 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6237 ADISPLAY_ID_DEFAULT);
6238 mDispatcher->notifyMotion(&motionArgs);
6239 window->assertNoEvents();
6240
6241 // When the window is no longer obscured because it went on top, it should get input
6242 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6243
6244 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6245 mDispatcher->notifyKey(&keyArgs);
6246 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6247
6248 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6249 ADISPLAY_ID_DEFAULT);
6250 mDispatcher->notifyMotion(&motionArgs);
6251 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6252 window->assertNoEvents();
6253}
6254
Antonio Kantekf16f2832021-09-28 04:39:20 +00006255class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6256protected:
6257 std::shared_ptr<FakeApplicationHandle> mApp;
6258 sp<FakeWindowHandle> mWindow;
6259 sp<FakeWindowHandle> mSecondWindow;
6260
6261 void SetUp() override {
6262 InputDispatcherTest::SetUp();
6263
6264 mApp = std::make_shared<FakeApplicationHandle>();
6265 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6266 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006267 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006268 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6269 mSecondWindow->setFocusable(true);
6270
6271 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6272 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006273 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006274
6275 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
6276 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, INJECTOR_PID,
6277 INJECTOR_UID, /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006278 }
6279
Antonio Kantekea47acb2021-12-23 12:41:25 -08006280 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006281 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006282 mWindow->consumeTouchModeEvent(inTouchMode);
6283 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6284 }
6285};
6286
Antonio Kantek26defcf2022-02-08 01:12:27 +00006287TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006288 const WindowInfo& windowInfo = *mWindow->getInfo();
6289 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6290 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006291}
6292
Antonio Kantek26defcf2022-02-08 01:12:27 +00006293TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6294 const WindowInfo& windowInfo = *mWindow->getInfo();
6295 int32_t ownerPid = windowInfo.ownerPid;
6296 int32_t ownerUid = windowInfo.ownerUid;
6297 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6298 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6299 ownerUid, /* hasPermission */ false));
6300 mWindow->assertNoEvents();
6301 mSecondWindow->assertNoEvents();
6302}
6303
6304TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6305 const WindowInfo& windowInfo = *mWindow->getInfo();
6306 int32_t ownerPid = windowInfo.ownerPid;
6307 int32_t ownerUid = windowInfo.ownerUid;
6308 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6309 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6310 /* hasPermission */ true);
6311}
6312
Antonio Kantekf16f2832021-09-28 04:39:20 +00006313TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006314 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006315 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6316 windowInfo.ownerPid, windowInfo.ownerUid,
6317 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006318 mWindow->assertNoEvents();
6319 mSecondWindow->assertNoEvents();
6320}
6321
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006322class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6323public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006324 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006325 std::shared_ptr<FakeApplicationHandle> application =
6326 std::make_shared<FakeApplicationHandle>();
6327 std::string name = "Fake Spy ";
6328 name += std::to_string(mSpyCount++);
6329 sp<FakeWindowHandle> spy =
6330 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
6331 spy->setInputFeatures(WindowInfo::Feature::SPY);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006332 spy->setTrustedOverlay(true);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006333 spy->setTouchModal(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006334 return spy;
6335 }
6336
6337 sp<FakeWindowHandle> createForeground() {
6338 std::shared_ptr<FakeApplicationHandle> application =
6339 std::make_shared<FakeApplicationHandle>();
6340 sp<FakeWindowHandle> window =
6341 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006342 window->setFocusable(true);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006343 window->setTouchModal(false);
6344 window->setSplitTouch(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006345 return window;
6346 }
6347
6348private:
6349 int mSpyCount{0};
6350};
6351
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006352using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006353/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006354 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6355 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006356TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6357 ScopedSilentDeath _silentDeath;
6358
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006359 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006360 spy->setTrustedOverlay(false);
6361 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6362 ".* not a trusted overlay");
6363}
6364
6365/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006366 * Input injection into a display with a spy window but no foreground windows should succeed.
6367 */
6368TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006369 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006370 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6371
6372 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6373 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6374 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6375 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6376}
6377
6378/**
6379 * Verify the order in which different input windows receive events. The touched foreground window
6380 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6381 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6382 * receive events before ones belows it.
6383 *
6384 * Here, we set up a scenario with four windows in the following Z order from the top:
6385 * spy1, spy2, window, spy3.
6386 * We then inject an event and verify that the foreground "window" receives it first, followed by
6387 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6388 * window.
6389 */
6390TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6391 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006392 auto spy1 = createSpy();
6393 auto spy2 = createSpy();
6394 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006395 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6396 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6397 const size_t numChannels = channels.size();
6398
Michael Wright8e9a8562022-02-09 13:44:29 +00006399 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006400 if (!epollFd.ok()) {
6401 FAIL() << "Failed to create epoll fd";
6402 }
6403
6404 for (size_t i = 0; i < numChannels; i++) {
6405 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6406 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6407 FAIL() << "Failed to add fd to epoll";
6408 }
6409 }
6410
6411 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6412 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6413 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6414
6415 std::vector<size_t> eventOrder;
6416 std::vector<struct epoll_event> events(numChannels);
6417 for (;;) {
6418 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6419 (100ms).count());
6420 if (nFds < 0) {
6421 FAIL() << "Failed to call epoll_wait";
6422 }
6423 if (nFds == 0) {
6424 break; // epoll_wait timed out
6425 }
6426 for (int i = 0; i < nFds; i++) {
6427 ASSERT_EQ(EPOLLIN, events[i].events);
6428 eventOrder.push_back(events[i].data.u64);
6429 channels[i]->consumeMotionDown();
6430 }
6431 }
6432
6433 // Verify the order in which the events were received.
6434 EXPECT_EQ(3u, eventOrder.size());
6435 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6436 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6437 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6438}
6439
6440/**
6441 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6442 */
6443TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6444 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006445 auto spy = createSpy();
6446 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006447 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6448
6449 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6450 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6451 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6452 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6453 spy->assertNoEvents();
6454}
6455
6456/**
6457 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6458 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6459 * to the window.
6460 */
6461TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6462 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006463 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006464 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6465 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6466
6467 // Inject an event outside the spy window's touchable region.
6468 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6469 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6470 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6471 window->consumeMotionDown();
6472 spy->assertNoEvents();
6473 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6474 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6475 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6476 window->consumeMotionUp();
6477 spy->assertNoEvents();
6478
6479 // Inject an event inside the spy window's touchable region.
6480 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6481 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6482 {5, 10}))
6483 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6484 window->consumeMotionDown();
6485 spy->consumeMotionDown();
6486}
6487
6488/**
6489 * A spy window that is a modal window will receive gestures outside of its frame and touchable
6490 * region.
6491 */
6492TEST_F(InputDispatcherSpyWindowTest, ModalWindow) {
6493 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006494 auto spy = createSpy();
6495 // Our current policy dictates that modal windows must be focusable.
6496 spy->setFocusable(true);
6497 spy->setTouchModal(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006498 spy->setFrame(Rect{0, 0, 20, 20});
6499 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6500
6501 // Inject an event outside the spy window's frame and touchable region.
6502 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6503 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6504 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6505 window->consumeMotionDown();
6506 spy->consumeMotionDown();
6507}
6508
6509/**
6510 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006511 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006512 */
6513TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6514 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006515 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006516 auto spy = createSpy();
6517 spy->setWatchOutsideTouch(true);
6518 spy->setTouchModal(false);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006519 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006520 spy->setFrame(Rect{0, 0, 20, 20});
6521 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6522
6523 // Inject an event outside the spy window's frame and touchable region.
6524 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006525 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6526 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006527 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6528 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006529 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006530}
6531
6532/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006533 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6534 * any other windows - including other spy windows - will also be cancelled.
6535 */
6536TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6537 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006538 auto spy1 = createSpy();
6539 auto spy2 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006540 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6541
6542 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6543 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6544 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6545 window->consumeMotionDown();
6546 spy1->consumeMotionDown();
6547 spy2->consumeMotionDown();
6548
6549 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006550 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006551 spy2->assertNoEvents();
6552 spy1->consumeMotionCancel();
6553 window->consumeMotionCancel();
6554
6555 // The rest of the gesture should only be sent to the second spy window.
6556 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6557 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6558 ADISPLAY_ID_DEFAULT))
6559 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6560 spy2->consumeMotionMove();
6561 spy1->assertNoEvents();
6562 window->assertNoEvents();
6563}
6564
6565/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006566 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
6567 * in the middle of the gesture.
6568 */
6569TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
6570 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006571 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006572 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6573
6574 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6575 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6576 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6577 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6578 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6579
6580 window->releaseChannel();
6581
6582 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6583
6584 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6585 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6586 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6587 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6588}
6589
6590/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006591 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
6592 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006593 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006594TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006595 auto spy = createSpy();
6596 spy->setTouchModal(false);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006597 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006598
6599 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6600
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006601 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006602 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6603 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6604 {100, 200}))
6605 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006606 spy->consumeMotionDown();
6607 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006608
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006609 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006610 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006611 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006612
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006613 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006614 const MotionEvent secondFingerDownEvent =
6615 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6616 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6617 AINPUT_SOURCE_TOUCHSCREEN)
6618 .displayId(ADISPLAY_ID_DEFAULT)
6619 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6620 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6621 .x(100)
6622 .y(200))
6623 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6624 .build();
6625 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6626 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6627 InputEventInjectionSync::WAIT_FOR_RESULT))
6628 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6629
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006630 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6631
6632 // Third finger goes down outside all windows, so injection should fail.
6633 const MotionEvent thirdFingerDownEvent =
6634 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6635 (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6636 AINPUT_SOURCE_TOUCHSCREEN)
6637 .displayId(ADISPLAY_ID_DEFAULT)
6638 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6639 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6640 .x(100)
6641 .y(200))
6642 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6643 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
6644 .build();
6645 ASSERT_EQ(InputEventInjectionResult::FAILED,
6646 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
6647 InputEventInjectionSync::WAIT_FOR_RESULT))
6648 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6649
6650 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006651 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006652}
6653
6654/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006655 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6656 * pointers that are down within its bounds.
6657 */
6658TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6659 auto windowLeft = createForeground();
6660 windowLeft->setFrame({0, 0, 100, 200});
6661 auto windowRight = createForeground();
6662 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006663 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006664 spy->setFrame({0, 0, 200, 200});
6665 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6666
6667 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6668 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6669 {50, 50}))
6670 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6671 windowLeft->consumeMotionDown();
6672 spy->consumeMotionDown();
6673
6674 const MotionEvent secondFingerDownEvent =
6675 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6676 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6677 AINPUT_SOURCE_TOUCHSCREEN)
6678 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6679 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6680 .pointer(
6681 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6682 .build();
6683 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6684 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6685 InputEventInjectionSync::WAIT_FOR_RESULT))
6686 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6687 windowRight->consumeMotionDown();
6688 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6689}
6690
6691/**
6692 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6693 * the spy should receive the second pointer with ACTION_DOWN.
6694 */
6695TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6696 auto window = createForeground();
6697 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006698 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006699 spyRight->setFrame({100, 0, 200, 200});
6700 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6701
6702 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6703 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6704 {50, 50}))
6705 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6706 window->consumeMotionDown();
6707 spyRight->assertNoEvents();
6708
6709 const MotionEvent secondFingerDownEvent =
6710 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6711 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6712 AINPUT_SOURCE_TOUCHSCREEN)
6713 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6714 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6715 .pointer(
6716 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6717 .build();
6718 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6719 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6720 InputEventInjectionSync::WAIT_FOR_RESULT))
6721 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6722 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6723 spyRight->consumeMotionDown();
6724}
6725
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006726/**
6727 * The spy window should not be able to affect whether or not touches are split. Only the foreground
6728 * windows should be allowed to control split touch.
6729 */
6730TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
6731 // Create a touch modal spy that spies on the entire display.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006732 // This spy window does not set split touch. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006733 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006734 auto spy = createSpy();
6735 spy->setTouchModal(true);
6736 spy->setSplitTouch(false);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006737
6738 // Create a non touch modal window that supports split touch.
6739 auto window = createForeground();
6740 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006741
6742 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6743
6744 // First finger down, no window touched.
6745 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6746 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6747 {100, 200}))
6748 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6749 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6750 window->assertNoEvents();
6751
6752 // Second finger down on window, the window should receive touch down.
6753 const MotionEvent secondFingerDownEvent =
6754 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6755 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6756 AINPUT_SOURCE_TOUCHSCREEN)
6757 .displayId(ADISPLAY_ID_DEFAULT)
6758 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6759 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6760 .x(100)
6761 .y(200))
6762 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6763 .build();
6764 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6765 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6766 InputEventInjectionSync::WAIT_FOR_RESULT))
6767 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6768
6769 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6770 spy->consumeMotionPointerDown(1 /* pointerIndex */);
6771}
6772
6773/**
6774 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
6775 * do not receive key events.
6776 */
6777TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006778 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006779 spy->setFocusable(false);
6780
6781 auto window = createForeground();
6782 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6783 setFocusedWindow(window);
6784 window->consumeFocusEvent(true);
6785
6786 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6787 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6788 window->consumeKeyDown(ADISPLAY_ID_NONE);
6789
6790 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6791 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6792 window->consumeKeyUp(ADISPLAY_ID_NONE);
6793
6794 spy->assertNoEvents();
6795}
6796
Prabir Pradhand65552b2021-10-07 11:23:50 -07006797class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6798public:
6799 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6800 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6801 std::make_shared<FakeApplicationHandle>();
6802 sp<FakeWindowHandle> overlay =
6803 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6804 ADISPLAY_ID_DEFAULT);
6805 overlay->setFocusable(false);
6806 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006807 overlay->setTouchable(false);
6808 overlay->setSplitTouch(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006809 overlay->setInputFeatures(WindowInfo::Feature::INTERCEPTS_STYLUS);
6810 overlay->setTrustedOverlay(true);
6811
6812 std::shared_ptr<FakeApplicationHandle> application =
6813 std::make_shared<FakeApplicationHandle>();
6814 sp<FakeWindowHandle> window =
6815 new FakeWindowHandle(application, mDispatcher, "Application window",
6816 ADISPLAY_ID_DEFAULT);
6817 window->setFocusable(true);
6818 window->setOwnerInfo(222, 222);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006819 window->setSplitTouch(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006820
6821 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6822 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6823 setFocusedWindow(window);
6824 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6825 return {std::move(overlay), std::move(window)};
6826 }
6827
6828 void sendFingerEvent(int32_t action) {
6829 NotifyMotionArgs motionArgs =
6830 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6831 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6832 mDispatcher->notifyMotion(&motionArgs);
6833 }
6834
6835 void sendStylusEvent(int32_t action) {
6836 NotifyMotionArgs motionArgs =
6837 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6838 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6839 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6840 mDispatcher->notifyMotion(&motionArgs);
6841 }
6842};
6843
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006844using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
6845
6846TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
6847 ScopedSilentDeath _silentDeath;
6848
Prabir Pradhand65552b2021-10-07 11:23:50 -07006849 auto [overlay, window] = setupStylusOverlayScenario();
6850 overlay->setTrustedOverlay(false);
6851 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6852 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6853 ".* not a trusted overlay");
6854}
6855
6856TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6857 auto [overlay, window] = setupStylusOverlayScenario();
6858 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6859
6860 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6861 overlay->consumeMotionDown();
6862 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6863 overlay->consumeMotionUp();
6864
6865 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6866 window->consumeMotionDown();
6867 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6868 window->consumeMotionUp();
6869
6870 overlay->assertNoEvents();
6871 window->assertNoEvents();
6872}
6873
6874TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6875 auto [overlay, window] = setupStylusOverlayScenario();
6876 overlay->setInputFeatures(overlay->getInfo()->inputFeatures | WindowInfo::Feature::SPY);
6877 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6878
6879 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6880 overlay->consumeMotionDown();
6881 window->consumeMotionDown();
6882 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6883 overlay->consumeMotionUp();
6884 window->consumeMotionUp();
6885
6886 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6887 window->consumeMotionDown();
6888 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6889 window->consumeMotionUp();
6890
6891 overlay->assertNoEvents();
6892 window->assertNoEvents();
6893}
6894
Garfield Tane84e6f92019-08-29 17:28:41 -07006895} // namespace android::inputdispatcher