blob: 51ecf763a10fe01f9fa2439656a813eae3109414 [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 Pradhan76bdecb2022-01-31 11:14:15 -08001003 mInfo.inputConfig = WindowInfo::InputConfig::NONE;
chaviwd1c23182019-12-20 18:44:56 -08001004 }
1005
Arthur Hungabbb9d82021-09-01 14:52:30 +00001006 sp<FakeWindowHandle> clone(
1007 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001008 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001009 sp<FakeWindowHandle> handle =
1010 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1011 displayId, mInfo.token);
1012 return handle;
1013 }
1014
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001015 void setTouchable(bool touchable) {
1016 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1017 }
chaviwd1c23182019-12-20 18:44:56 -08001018
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001019 void setFocusable(bool focusable) {
1020 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1021 }
1022
1023 void setVisible(bool visible) {
1024 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1025 }
Vishnu Nair958da932020-08-21 17:12:37 -07001026
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001027 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001028 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001029 }
1030
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001031 void setPaused(bool paused) {
1032 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1033 }
1034
1035 void setTouchModal(bool touchModal) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001036 mInfo.setInputConfig(WindowInfo::InputConfig::TOUCH_MODAL, touchModal);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001037 }
1038
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001039 void setPreventSplitting(bool preventSplitting) {
1040 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001041 }
1042
1043 void setSlippery(bool slippery) {
1044 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1045 }
1046
1047 void setWatchOutsideTouch(bool watchOutside) {
1048 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1049 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001050
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001051 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1052
chaviw3277faf2021-05-19 16:45:23 -05001053 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001054
Bernardo Rufino7393d172021-02-26 13:56:11 +00001055 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1056
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001057 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001058 mInfo.frameLeft = frame.left;
1059 mInfo.frameTop = frame.top;
1060 mInfo.frameRight = frame.right;
1061 mInfo.frameBottom = frame.bottom;
1062 mInfo.touchableRegion.clear();
1063 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001064
1065 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1066 ui::Transform translate;
1067 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1068 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001069 }
1070
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001071 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1072
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001073 void setIsWallpaper(bool isWallpaper) {
1074 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1075 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001076
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001077 void setDupTouchToWallpaper(bool hasWallpaper) {
1078 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1079 }
chaviwd1c23182019-12-20 18:44:56 -08001080
Prabir Pradhand65552b2021-10-07 11:23:50 -07001081 void setInputFeatures(Flags<WindowInfo::Feature> features) { mInfo.inputFeatures = features; }
1082
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001083 void setTrustedOverlay(bool trustedOverlay) {
1084 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1085 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001086
chaviw9eaa22c2020-07-01 16:21:27 -07001087 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1088 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1089 }
1090
1091 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001092
yunho.shinf4a80b82020-11-16 21:13:57 +09001093 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1094
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001095 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1096 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1097 expectedFlags);
1098 }
1099
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001100 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1101 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1102 }
1103
Svet Ganov5d3bc372020-01-26 23:11:07 -08001104 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001105 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001106 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1107 expectedFlags);
1108 }
1109
1110 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001111 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001112 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1113 expectedFlags);
1114 }
1115
1116 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001117 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001118 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1119 }
1120
1121 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1122 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001123 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1124 expectedFlags);
1125 }
1126
Svet Ganov5d3bc372020-01-26 23:11:07 -08001127 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001128 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1129 int32_t expectedFlags = 0) {
1130 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1131 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001132 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1133 }
1134
1135 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001136 int32_t expectedFlags = 0) {
1137 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1138 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001139 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1140 }
1141
1142 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001143 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001144 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1145 expectedFlags);
1146 }
1147
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001148 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1149 int32_t expectedFlags = 0) {
1150 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1151 expectedFlags);
1152 }
1153
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001154 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1155 int32_t expectedFlags = 0) {
1156 InputEvent* event = consume();
1157 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1158 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1159 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1160 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1161 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1162 }
1163
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001164 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1165 ASSERT_NE(mInputReceiver, nullptr)
1166 << "Cannot consume events from a window with no receiver";
1167 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1168 }
1169
Prabir Pradhan99987712020-11-10 18:43:05 -08001170 void consumeCaptureEvent(bool hasCapture) {
1171 ASSERT_NE(mInputReceiver, nullptr)
1172 << "Cannot consume events from a window with no receiver";
1173 mInputReceiver->consumeCaptureEvent(hasCapture);
1174 }
1175
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001176 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1177 std::optional<int32_t> expectedDisplayId,
1178 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001179 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1180 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1181 expectedFlags);
1182 }
1183
arthurhungb89ccb02020-12-30 16:19:01 +08001184 void consumeDragEvent(bool isExiting, float x, float y) {
1185 mInputReceiver->consumeDragEvent(isExiting, x, y);
1186 }
1187
Antonio Kantekf16f2832021-09-28 04:39:20 +00001188 void consumeTouchModeEvent(bool inTouchMode) {
1189 ASSERT_NE(mInputReceiver, nullptr)
1190 << "Cannot consume events from a window with no receiver";
1191 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1192 }
1193
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001194 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001195 if (mInputReceiver == nullptr) {
1196 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1197 return std::nullopt;
1198 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001199 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001200 }
1201
1202 void finishEvent(uint32_t sequenceNum) {
1203 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1204 mInputReceiver->finishEvent(sequenceNum);
1205 }
1206
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001207 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1208 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1209 mInputReceiver->sendTimeline(inputEventId, timeline);
1210 }
1211
chaviwaf87b3e2019-10-01 16:59:28 -07001212 InputEvent* consume() {
1213 if (mInputReceiver == nullptr) {
1214 return nullptr;
1215 }
1216 return mInputReceiver->consume();
1217 }
1218
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001219 MotionEvent* consumeMotion() {
1220 InputEvent* event = consume();
1221 if (event == nullptr) {
1222 ADD_FAILURE() << "Consume failed : no event";
1223 return nullptr;
1224 }
1225 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1226 ADD_FAILURE() << "Instead of motion event, got "
1227 << inputEventTypeToString(event->getType());
1228 return nullptr;
1229 }
1230 return static_cast<MotionEvent*>(event);
1231 }
1232
Arthur Hungb92218b2018-08-14 12:00:21 +08001233 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001234 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001235 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001236 return; // Can't receive events if the window does not have input channel
1237 }
1238 ASSERT_NE(nullptr, mInputReceiver)
1239 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001240 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001241 }
1242
chaviwaf87b3e2019-10-01 16:59:28 -07001243 sp<IBinder> getToken() { return mInfo.token; }
1244
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001245 const std::string& getName() { return mName; }
1246
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001247 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1248 mInfo.ownerPid = ownerPid;
1249 mInfo.ownerUid = ownerUid;
1250 }
1251
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001252 void destroyReceiver() { mInputReceiver = nullptr; }
1253
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001254 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1255
chaviwd1c23182019-12-20 18:44:56 -08001256private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001257 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001258 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001259 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001260};
1261
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001262std::atomic<int32_t> FakeWindowHandle::sId{1};
1263
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001264static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001265 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001266 int32_t displayId = ADISPLAY_ID_NONE,
1267 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001268 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1269 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001270 KeyEvent event;
1271 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1272
1273 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001274 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001275 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1276 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001277
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001278 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1279 if (!allowKeyRepeat) {
1280 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1281 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001282 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001283 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001284 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001285}
1286
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001287static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001288 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001289 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1290}
1291
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001292// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1293// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1294// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001295static InputEventInjectionResult injectKeyDownNoRepeat(
1296 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001297 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1298 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1299 /* allowKeyRepeat */ false);
1300}
1301
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001302static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001303 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001304 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1305}
1306
Garfield Tandf26e862020-07-01 20:18:19 -07001307class PointerBuilder {
1308public:
1309 PointerBuilder(int32_t id, int32_t toolType) {
1310 mProperties.clear();
1311 mProperties.id = id;
1312 mProperties.toolType = toolType;
1313 mCoords.clear();
1314 }
1315
1316 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1317
1318 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1319
1320 PointerBuilder& axis(int32_t axis, float value) {
1321 mCoords.setAxisValue(axis, value);
1322 return *this;
1323 }
1324
1325 PointerProperties buildProperties() const { return mProperties; }
1326
1327 PointerCoords buildCoords() const { return mCoords; }
1328
1329private:
1330 PointerProperties mProperties;
1331 PointerCoords mCoords;
1332};
1333
1334class MotionEventBuilder {
1335public:
1336 MotionEventBuilder(int32_t action, int32_t source) {
1337 mAction = action;
1338 mSource = source;
1339 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1340 }
1341
1342 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1343 mEventTime = eventTime;
1344 return *this;
1345 }
1346
1347 MotionEventBuilder& displayId(int32_t displayId) {
1348 mDisplayId = displayId;
1349 return *this;
1350 }
1351
1352 MotionEventBuilder& actionButton(int32_t actionButton) {
1353 mActionButton = actionButton;
1354 return *this;
1355 }
1356
arthurhung6d4bed92021-03-17 11:59:33 +08001357 MotionEventBuilder& buttonState(int32_t buttonState) {
1358 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001359 return *this;
1360 }
1361
1362 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1363 mRawXCursorPosition = rawXCursorPosition;
1364 return *this;
1365 }
1366
1367 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1368 mRawYCursorPosition = rawYCursorPosition;
1369 return *this;
1370 }
1371
1372 MotionEventBuilder& pointer(PointerBuilder pointer) {
1373 mPointers.push_back(pointer);
1374 return *this;
1375 }
1376
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001377 MotionEventBuilder& addFlag(uint32_t flags) {
1378 mFlags |= flags;
1379 return *this;
1380 }
1381
Garfield Tandf26e862020-07-01 20:18:19 -07001382 MotionEvent build() {
1383 std::vector<PointerProperties> pointerProperties;
1384 std::vector<PointerCoords> pointerCoords;
1385 for (const PointerBuilder& pointer : mPointers) {
1386 pointerProperties.push_back(pointer.buildProperties());
1387 pointerCoords.push_back(pointer.buildCoords());
1388 }
1389
1390 // Set mouse cursor position for the most common cases to avoid boilerplate.
1391 if (mSource == AINPUT_SOURCE_MOUSE &&
1392 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1393 mPointers.size() == 1) {
1394 mRawXCursorPosition = pointerCoords[0].getX();
1395 mRawYCursorPosition = pointerCoords[0].getY();
1396 }
1397
1398 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001399 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001400 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001401 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001402 mButtonState, MotionClassification::NONE, identityTransform,
1403 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001404 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1405 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001406
1407 return event;
1408 }
1409
1410private:
1411 int32_t mAction;
1412 int32_t mSource;
1413 nsecs_t mEventTime;
1414 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1415 int32_t mActionButton{0};
1416 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001417 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001418 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1419 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1420
1421 std::vector<PointerBuilder> mPointers;
1422};
1423
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001424static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001425 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001426 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001427 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001428 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1429 injectionTimeout,
1430 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1431}
1432
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001433static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001434 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001435 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001436 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001437 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1438 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001439 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001440 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001441 MotionEvent event = MotionEventBuilder(action, source)
1442 .displayId(displayId)
1443 .eventTime(eventTime)
1444 .rawXCursorPosition(cursorPosition.x)
1445 .rawYCursorPosition(cursorPosition.y)
1446 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1447 .x(position.x)
1448 .y(position.y))
1449 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001450
1451 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001452 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001453}
1454
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001455static InputEventInjectionResult injectMotionDown(
1456 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1457 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001458 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001459}
1460
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001461static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001462 int32_t source, int32_t displayId,
1463 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001464 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001465}
1466
Jackal Guof9696682018-10-05 12:23:23 +08001467static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1468 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1469 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001470 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1471 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1472 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001473
1474 return args;
1475}
1476
chaviwd1c23182019-12-20 18:44:56 -08001477static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1478 const std::vector<PointF>& points) {
1479 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001480 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1481 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1482 }
1483
chaviwd1c23182019-12-20 18:44:56 -08001484 PointerProperties pointerProperties[pointerCount];
1485 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001486
chaviwd1c23182019-12-20 18:44:56 -08001487 for (size_t i = 0; i < pointerCount; i++) {
1488 pointerProperties[i].clear();
1489 pointerProperties[i].id = i;
1490 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001491
chaviwd1c23182019-12-20 18:44:56 -08001492 pointerCoords[i].clear();
1493 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1494 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1495 }
Jackal Guof9696682018-10-05 12:23:23 +08001496
1497 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1498 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001499 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001500 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1501 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001502 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1503 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001504 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1505 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001506
1507 return args;
1508}
1509
chaviwd1c23182019-12-20 18:44:56 -08001510static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1511 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1512}
1513
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001514static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1515 const PointerCaptureRequest& request) {
1516 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001517}
1518
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001519/**
1520 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1521 * broken channel.
1522 */
1523TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1524 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1525 sp<FakeWindowHandle> window =
1526 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1527 ADISPLAY_ID_DEFAULT);
1528
1529 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1530
1531 // Window closes its channel, but the window remains.
1532 window->destroyReceiver();
1533 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1534}
1535
Arthur Hungb92218b2018-08-14 12:00:21 +08001536TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001537 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001538 sp<FakeWindowHandle> window =
1539 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001540
Arthur Hung72d8dc32020-03-28 00:48:39 +00001541 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001542 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1543 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1544 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001545
1546 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001547 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001548}
1549
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001550TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1551 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1552 sp<FakeWindowHandle> window =
1553 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1554
1555 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1556 // Inject a MotionEvent to an unknown display.
1557 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1558 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1559 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1560
1561 // Window should receive motion event.
1562 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1563}
1564
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001565/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001566 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001567 * This test serves as a sanity check for the next test, where setInputWindows is
1568 * called twice.
1569 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001570TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001571 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001572 sp<FakeWindowHandle> window =
1573 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1574 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001575
1576 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001577 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001578 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1579 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001580 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001581
1582 // Window should receive motion event.
1583 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1584}
1585
1586/**
1587 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001588 */
1589TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001590 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001591 sp<FakeWindowHandle> window =
1592 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1593 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001594
1595 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1596 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001597 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001598 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1599 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001600 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001601
1602 // Window should receive motion event.
1603 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1604}
1605
Arthur Hungb92218b2018-08-14 12:00:21 +08001606// The foreground window should receive the first touch down event.
1607TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001608 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001609 sp<FakeWindowHandle> windowTop =
1610 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1611 sp<FakeWindowHandle> windowSecond =
1612 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001613
Arthur Hung72d8dc32020-03-28 00:48:39 +00001614 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001615 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1616 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1617 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001618
1619 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001620 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001621 windowSecond->assertNoEvents();
1622}
1623
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001624/**
1625 * Two windows: A top window, and a wallpaper behind the window.
1626 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1627 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001628 * 1. foregroundWindow <-- dup touch to wallpaper
1629 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001630 */
1631TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1632 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1633 sp<FakeWindowHandle> foregroundWindow =
1634 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001635 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001636 sp<FakeWindowHandle> wallpaperWindow =
1637 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001638 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001639 constexpr int expectedWallpaperFlags =
1640 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1641
1642 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1643 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1644 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1645 {100, 200}))
1646 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1647
1648 // Both foreground window and its wallpaper should receive the touch down
1649 foregroundWindow->consumeMotionDown();
1650 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1651
1652 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1653 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1654 ADISPLAY_ID_DEFAULT, {110, 200}))
1655 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1656
1657 foregroundWindow->consumeMotionMove();
1658 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1659
1660 // Now the foreground window goes away, but the wallpaper stays
1661 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1662 foregroundWindow->consumeMotionCancel();
1663 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1664 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1665}
1666
1667/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001668 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1669 * with the following differences:
1670 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1671 * clean up the connection.
1672 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1673 * Ensure that there's no crash in the dispatcher.
1674 */
1675TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1676 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1677 sp<FakeWindowHandle> foregroundWindow =
1678 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001679 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001680 sp<FakeWindowHandle> wallpaperWindow =
1681 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001682 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001683 constexpr int expectedWallpaperFlags =
1684 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1685
1686 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1687 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1688 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1689 {100, 200}))
1690 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1691
1692 // Both foreground window and its wallpaper should receive the touch down
1693 foregroundWindow->consumeMotionDown();
1694 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1695
1696 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1697 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1698 ADISPLAY_ID_DEFAULT, {110, 200}))
1699 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1700
1701 foregroundWindow->consumeMotionMove();
1702 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1703
1704 // Wallpaper closes its channel, but the window remains.
1705 wallpaperWindow->destroyReceiver();
1706 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1707
1708 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1709 // is no longer valid.
1710 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1711 foregroundWindow->consumeMotionCancel();
1712}
1713
1714/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001715 * A single window that receives touch (on top), and a wallpaper window underneath it.
1716 * The top window gets a multitouch gesture.
1717 * Ensure that wallpaper gets the same gesture.
1718 */
1719TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1720 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1721 sp<FakeWindowHandle> window =
1722 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001723 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001724
1725 sp<FakeWindowHandle> wallpaperWindow =
1726 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001727 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001728 constexpr int expectedWallpaperFlags =
1729 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1730
1731 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1732
1733 // Touch down on top window
1734 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1735 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1736 {100, 100}))
1737 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1738
1739 // Both top window and its wallpaper should receive the touch down
1740 window->consumeMotionDown();
1741 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1742
1743 // Second finger down on the top window
1744 const MotionEvent secondFingerDownEvent =
1745 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1746 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1747 AINPUT_SOURCE_TOUCHSCREEN)
1748 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1749 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1750 .x(100)
1751 .y(100))
1752 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1753 .x(150)
1754 .y(150))
1755 .build();
1756 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1757 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1758 InputEventInjectionSync::WAIT_FOR_RESULT))
1759 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1760
1761 window->consumeMotionPointerDown(1 /* pointerIndex */);
1762 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1763 expectedWallpaperFlags);
1764 window->assertNoEvents();
1765 wallpaperWindow->assertNoEvents();
1766}
1767
1768/**
1769 * Two windows: a window on the left and window on the right.
1770 * A third window, wallpaper, is behind both windows, and spans both top windows.
1771 * The first touch down goes to the left window. A second pointer touches down on the right window.
1772 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1773 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1774 * ACTION_POINTER_DOWN(1).
1775 */
1776TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1777 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1778 sp<FakeWindowHandle> leftWindow =
1779 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1780 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001781 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001782
1783 sp<FakeWindowHandle> rightWindow =
1784 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1785 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001786 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001787
1788 sp<FakeWindowHandle> wallpaperWindow =
1789 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1790 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001791 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001792 constexpr int expectedWallpaperFlags =
1793 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1794
1795 mDispatcher->setInputWindows(
1796 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1797
1798 // Touch down on left window
1799 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1800 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1801 {100, 100}))
1802 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1803
1804 // Both foreground window and its wallpaper should receive the touch down
1805 leftWindow->consumeMotionDown();
1806 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1807
1808 // Second finger down on the right window
1809 const MotionEvent secondFingerDownEvent =
1810 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1811 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1812 AINPUT_SOURCE_TOUCHSCREEN)
1813 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1814 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1815 .x(100)
1816 .y(100))
1817 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1818 .x(300)
1819 .y(100))
1820 .build();
1821 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1822 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1823 InputEventInjectionSync::WAIT_FOR_RESULT))
1824 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1825
1826 leftWindow->consumeMotionMove();
1827 // Since the touch is split, right window gets ACTION_DOWN
1828 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1829 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1830 expectedWallpaperFlags);
1831
1832 // Now, leftWindow, which received the first finger, disappears.
1833 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1834 leftWindow->consumeMotionCancel();
1835 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1836 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1837
1838 // The pointer that's still down on the right window moves, and goes to the right window only.
1839 // As far as the dispatcher's concerned though, both pointers are still present.
1840 const MotionEvent secondFingerMoveEvent =
1841 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1842 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1843 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1844 .x(100)
1845 .y(100))
1846 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1847 .x(310)
1848 .y(110))
1849 .build();
1850 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1851 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1852 InputEventInjectionSync::WAIT_FOR_RESULT));
1853 rightWindow->consumeMotionMove();
1854
1855 leftWindow->assertNoEvents();
1856 rightWindow->assertNoEvents();
1857 wallpaperWindow->assertNoEvents();
1858}
1859
Garfield Tandf26e862020-07-01 20:18:19 -07001860TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001861 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001862 sp<FakeWindowHandle> windowLeft =
1863 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1864 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001865 sp<FakeWindowHandle> windowRight =
1866 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1867 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001868
1869 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1870
1871 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1872
1873 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001874 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001875 injectMotionEvent(mDispatcher,
1876 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1877 AINPUT_SOURCE_MOUSE)
1878 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1879 .x(900)
1880 .y(400))
1881 .build()));
1882 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1883 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1884 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1885 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1886
1887 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001888 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001889 injectMotionEvent(mDispatcher,
1890 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1891 AINPUT_SOURCE_MOUSE)
1892 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1893 .x(300)
1894 .y(400))
1895 .build()));
1896 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1897 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1898 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1899 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1900 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1901 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1902
1903 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001904 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001905 injectMotionEvent(mDispatcher,
1906 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1907 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1908 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1909 .x(300)
1910 .y(400))
1911 .build()));
1912 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1913
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001914 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001915 injectMotionEvent(mDispatcher,
1916 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1917 AINPUT_SOURCE_MOUSE)
1918 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1919 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1920 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1921 .x(300)
1922 .y(400))
1923 .build()));
1924 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1925 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1926
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001927 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001928 injectMotionEvent(mDispatcher,
1929 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1930 AINPUT_SOURCE_MOUSE)
1931 .buttonState(0)
1932 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1933 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1934 .x(300)
1935 .y(400))
1936 .build()));
1937 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1938 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1939
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001940 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001941 injectMotionEvent(mDispatcher,
1942 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1943 .buttonState(0)
1944 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1945 .x(300)
1946 .y(400))
1947 .build()));
1948 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1949
1950 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001951 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001952 injectMotionEvent(mDispatcher,
1953 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1954 AINPUT_SOURCE_MOUSE)
1955 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1956 .x(900)
1957 .y(400))
1958 .build()));
1959 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1960 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1961 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1962 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1963 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1964 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1965}
1966
1967// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1968// directly in this test.
1969TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001970 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001971 sp<FakeWindowHandle> window =
1972 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1973 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001974
1975 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1976
1977 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1978
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001979 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001980 injectMotionEvent(mDispatcher,
1981 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1982 AINPUT_SOURCE_MOUSE)
1983 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1984 .x(300)
1985 .y(400))
1986 .build()));
1987 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1988 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1989
1990 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001991 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001992 injectMotionEvent(mDispatcher,
1993 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1994 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1995 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1996 .x(300)
1997 .y(400))
1998 .build()));
1999 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2000
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002001 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002002 injectMotionEvent(mDispatcher,
2003 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2004 AINPUT_SOURCE_MOUSE)
2005 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2006 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2007 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2008 .x(300)
2009 .y(400))
2010 .build()));
2011 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2012 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2013
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002014 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002015 injectMotionEvent(mDispatcher,
2016 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2017 AINPUT_SOURCE_MOUSE)
2018 .buttonState(0)
2019 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2020 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2021 .x(300)
2022 .y(400))
2023 .build()));
2024 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2025 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2026
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002027 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002028 injectMotionEvent(mDispatcher,
2029 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2030 .buttonState(0)
2031 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2032 .x(300)
2033 .y(400))
2034 .build()));
2035 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2036
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002037 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002038 injectMotionEvent(mDispatcher,
2039 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2040 AINPUT_SOURCE_MOUSE)
2041 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2042 .x(300)
2043 .y(400))
2044 .build()));
2045 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2046 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2047}
2048
Garfield Tan00f511d2019-06-12 16:55:40 -07002049TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002050 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002051
2052 sp<FakeWindowHandle> windowLeft =
2053 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2054 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002055 sp<FakeWindowHandle> windowRight =
2056 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2057 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002058
2059 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2060
Arthur Hung72d8dc32020-03-28 00:48:39 +00002061 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002062
2063 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2064 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002065 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002066 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002067 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002068 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002069 windowRight->assertNoEvents();
2070}
2071
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002072TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002073 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002074 sp<FakeWindowHandle> window =
2075 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002076 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002077
Arthur Hung72d8dc32020-03-28 00:48:39 +00002078 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002079 setFocusedWindow(window);
2080
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002081 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002082
2083 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2084 mDispatcher->notifyKey(&keyArgs);
2085
2086 // Window should receive key down event.
2087 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2088
2089 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2090 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002091 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002092 mDispatcher->notifyDeviceReset(&args);
2093 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2094 AKEY_EVENT_FLAG_CANCELED);
2095}
2096
2097TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002098 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002099 sp<FakeWindowHandle> window =
2100 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2101
Arthur Hung72d8dc32020-03-28 00:48:39 +00002102 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002103
2104 NotifyMotionArgs motionArgs =
2105 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2106 ADISPLAY_ID_DEFAULT);
2107 mDispatcher->notifyMotion(&motionArgs);
2108
2109 // Window should receive motion down event.
2110 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2111
2112 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2113 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002114 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002115 mDispatcher->notifyDeviceReset(&args);
2116 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2117 0 /*expectedFlags*/);
2118}
2119
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002120/**
2121 * Ensure the correct coordinate spaces are used by InputDispatcher.
2122 *
2123 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2124 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2125 * space.
2126 */
2127class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2128public:
2129 void SetUp() override {
2130 InputDispatcherTest::SetUp();
2131 mDisplayInfos.clear();
2132 mWindowInfos.clear();
2133 }
2134
2135 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2136 gui::DisplayInfo info;
2137 info.displayId = displayId;
2138 info.transform = transform;
2139 mDisplayInfos.push_back(std::move(info));
2140 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2141 }
2142
2143 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2144 mWindowInfos.push_back(*windowHandle->getInfo());
2145 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2146 }
2147
2148 // Set up a test scenario where the display has a scaled projection and there are two windows
2149 // on the display.
2150 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2151 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2152 // respectively.
2153 ui::Transform displayTransform;
2154 displayTransform.set(2, 0, 0, 4);
2155 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2156
2157 std::shared_ptr<FakeApplicationHandle> application =
2158 std::make_shared<FakeApplicationHandle>();
2159
2160 // Add two windows to the display. Their frames are represented in the display space.
2161 sp<FakeWindowHandle> firstWindow =
2162 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002163 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2164 addWindow(firstWindow);
2165
2166 sp<FakeWindowHandle> secondWindow =
2167 new FakeWindowHandle(application, mDispatcher, "Second Window",
2168 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002169 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2170 addWindow(secondWindow);
2171 return {std::move(firstWindow), std::move(secondWindow)};
2172 }
2173
2174private:
2175 std::vector<gui::DisplayInfo> mDisplayInfos;
2176 std::vector<gui::WindowInfo> mWindowInfos;
2177};
2178
2179TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2180 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2181 // Send down to the first window. The point is represented in the display space. The point is
2182 // selected so that if the hit test was done with the transform applied to it, then it would
2183 // end up in the incorrect window.
2184 NotifyMotionArgs downMotionArgs =
2185 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2186 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2187 mDispatcher->notifyMotion(&downMotionArgs);
2188
2189 firstWindow->consumeMotionDown();
2190 secondWindow->assertNoEvents();
2191}
2192
2193// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2194// the event should be treated as being in the logical display space.
2195TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2196 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2197 // Send down to the first window. The point is represented in the logical display space. The
2198 // point is selected so that if the hit test was done in logical display space, then it would
2199 // end up in the incorrect window.
2200 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2201 PointF{75 * 2, 55 * 4});
2202
2203 firstWindow->consumeMotionDown();
2204 secondWindow->assertNoEvents();
2205}
2206
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002207// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2208// event should be treated as being in the logical display space.
2209TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2210 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2211
2212 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2213 ui::Transform injectedEventTransform;
2214 injectedEventTransform.set(matrix);
2215 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2216 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2217
2218 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2219 .displayId(ADISPLAY_ID_DEFAULT)
2220 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2221 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2222 .x(untransformedPoint.x)
2223 .y(untransformedPoint.y))
2224 .build();
2225 event.transform(matrix);
2226
2227 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2228 InputEventInjectionSync::WAIT_FOR_RESULT);
2229
2230 firstWindow->consumeMotionDown();
2231 secondWindow->assertNoEvents();
2232}
2233
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002234TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2235 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2236
2237 // Send down to the second window.
2238 NotifyMotionArgs downMotionArgs =
2239 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2240 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2241 mDispatcher->notifyMotion(&downMotionArgs);
2242
2243 firstWindow->assertNoEvents();
2244 const MotionEvent* event = secondWindow->consumeMotion();
2245 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2246
2247 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2248 EXPECT_EQ(300, event->getRawX(0));
2249 EXPECT_EQ(880, event->getRawY(0));
2250
2251 // Ensure that the x and y values are in the window's coordinate space.
2252 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2253 // the logical display space. This will be the origin of the window space.
2254 EXPECT_EQ(100, event->getX(0));
2255 EXPECT_EQ(80, event->getY(0));
2256}
2257
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002258using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2259 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002260
2261class TransferTouchFixture : public InputDispatcherTest,
2262 public ::testing::WithParamInterface<TransferFunction> {};
2263
2264TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002265 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002266
2267 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002268 sp<FakeWindowHandle> firstWindow =
2269 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2270 sp<FakeWindowHandle> secondWindow =
2271 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002272
2273 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002274 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002275
2276 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002277 NotifyMotionArgs downMotionArgs =
2278 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2279 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002280 mDispatcher->notifyMotion(&downMotionArgs);
2281 // Only the first window should get the down event
2282 firstWindow->consumeMotionDown();
2283 secondWindow->assertNoEvents();
2284
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002285 // Transfer touch to the second window
2286 TransferFunction f = GetParam();
2287 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2288 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002289 // The first window gets cancel and the second gets down
2290 firstWindow->consumeMotionCancel();
2291 secondWindow->consumeMotionDown();
2292
2293 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002294 NotifyMotionArgs upMotionArgs =
2295 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2296 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002297 mDispatcher->notifyMotion(&upMotionArgs);
2298 // The first window gets no events and the second gets up
2299 firstWindow->assertNoEvents();
2300 secondWindow->consumeMotionUp();
2301}
2302
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002303TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002304 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002305
2306 PointF touchPoint = {10, 10};
2307
2308 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002309 sp<FakeWindowHandle> firstWindow =
2310 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002311 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002312 sp<FakeWindowHandle> secondWindow =
2313 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002314 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002315
2316 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002317 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002318
2319 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002320 NotifyMotionArgs downMotionArgs =
2321 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2322 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002323 mDispatcher->notifyMotion(&downMotionArgs);
2324 // Only the first window should get the down event
2325 firstWindow->consumeMotionDown();
2326 secondWindow->assertNoEvents();
2327
2328 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002329 NotifyMotionArgs pointerDownMotionArgs =
2330 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2331 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2332 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2333 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002334 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2335 // Only the first window should get the pointer down event
2336 firstWindow->consumeMotionPointerDown(1);
2337 secondWindow->assertNoEvents();
2338
2339 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002340 TransferFunction f = GetParam();
2341 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2342 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002343 // The first window gets cancel and the second gets down and pointer down
2344 firstWindow->consumeMotionCancel();
2345 secondWindow->consumeMotionDown();
2346 secondWindow->consumeMotionPointerDown(1);
2347
2348 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002349 NotifyMotionArgs pointerUpMotionArgs =
2350 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2351 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2352 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2353 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002354 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2355 // The first window gets nothing and the second gets pointer up
2356 firstWindow->assertNoEvents();
2357 secondWindow->consumeMotionPointerUp(1);
2358
2359 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002360 NotifyMotionArgs upMotionArgs =
2361 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2362 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002363 mDispatcher->notifyMotion(&upMotionArgs);
2364 // The first window gets nothing and the second gets up
2365 firstWindow->assertNoEvents();
2366 secondWindow->consumeMotionUp();
2367}
2368
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002369// For the cases of single pointer touch and two pointers non-split touch, the api's
2370// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2371// for the case where there are multiple pointers split across several windows.
2372INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2373 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002374 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2375 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002376 return dispatcher->transferTouch(destChannelToken);
2377 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002378 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2379 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002380 return dispatcher->transferTouchFocus(from, to,
2381 false /*isDragAndDrop*/);
2382 }));
2383
Svet Ganov5d3bc372020-01-26 23:11:07 -08002384TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002385 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002386
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002387 sp<FakeWindowHandle> firstWindow =
2388 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002389 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002390
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002391 sp<FakeWindowHandle> secondWindow =
2392 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002393 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002394
2395 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002396 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002397
2398 PointF pointInFirst = {300, 200};
2399 PointF pointInSecond = {300, 600};
2400
2401 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002402 NotifyMotionArgs firstDownMotionArgs =
2403 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2404 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002405 mDispatcher->notifyMotion(&firstDownMotionArgs);
2406 // Only the first window should get the down event
2407 firstWindow->consumeMotionDown();
2408 secondWindow->assertNoEvents();
2409
2410 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002411 NotifyMotionArgs secondDownMotionArgs =
2412 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2413 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2414 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2415 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002416 mDispatcher->notifyMotion(&secondDownMotionArgs);
2417 // The first window gets a move and the second a down
2418 firstWindow->consumeMotionMove();
2419 secondWindow->consumeMotionDown();
2420
2421 // Transfer touch focus to the second window
2422 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2423 // The first window gets cancel and the new gets pointer down (it already saw down)
2424 firstWindow->consumeMotionCancel();
2425 secondWindow->consumeMotionPointerDown(1);
2426
2427 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002428 NotifyMotionArgs pointerUpMotionArgs =
2429 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2430 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2431 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2432 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002433 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2434 // The first window gets nothing and the second gets pointer up
2435 firstWindow->assertNoEvents();
2436 secondWindow->consumeMotionPointerUp(1);
2437
2438 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002439 NotifyMotionArgs upMotionArgs =
2440 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2441 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002442 mDispatcher->notifyMotion(&upMotionArgs);
2443 // The first window gets nothing and the second gets up
2444 firstWindow->assertNoEvents();
2445 secondWindow->consumeMotionUp();
2446}
2447
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002448// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2449// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2450// touch is not supported, so the touch should continue on those windows and the transferred-to
2451// window should get nothing.
2452TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2453 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2454
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002455 sp<FakeWindowHandle> firstWindow =
2456 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2457 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002458
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002459 sp<FakeWindowHandle> secondWindow =
2460 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2461 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002462
2463 // Add the windows to the dispatcher
2464 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2465
2466 PointF pointInFirst = {300, 200};
2467 PointF pointInSecond = {300, 600};
2468
2469 // Send down to the first window
2470 NotifyMotionArgs firstDownMotionArgs =
2471 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2472 ADISPLAY_ID_DEFAULT, {pointInFirst});
2473 mDispatcher->notifyMotion(&firstDownMotionArgs);
2474 // Only the first window should get the down event
2475 firstWindow->consumeMotionDown();
2476 secondWindow->assertNoEvents();
2477
2478 // Send down to the second window
2479 NotifyMotionArgs secondDownMotionArgs =
2480 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2481 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2482 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2483 {pointInFirst, pointInSecond});
2484 mDispatcher->notifyMotion(&secondDownMotionArgs);
2485 // The first window gets a move and the second a down
2486 firstWindow->consumeMotionMove();
2487 secondWindow->consumeMotionDown();
2488
2489 // Transfer touch focus to the second window
2490 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2491 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2492 ASSERT_FALSE(transferred);
2493 firstWindow->assertNoEvents();
2494 secondWindow->assertNoEvents();
2495
2496 // The rest of the dispatch should proceed as normal
2497 // Send pointer up to the second window
2498 NotifyMotionArgs pointerUpMotionArgs =
2499 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2500 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2501 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2502 {pointInFirst, pointInSecond});
2503 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2504 // The first window gets MOVE and the second gets pointer up
2505 firstWindow->consumeMotionMove();
2506 secondWindow->consumeMotionUp();
2507
2508 // Send up event to the first window
2509 NotifyMotionArgs upMotionArgs =
2510 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2511 ADISPLAY_ID_DEFAULT);
2512 mDispatcher->notifyMotion(&upMotionArgs);
2513 // The first window gets nothing and the second gets up
2514 firstWindow->consumeMotionUp();
2515 secondWindow->assertNoEvents();
2516}
2517
Arthur Hungabbb9d82021-09-01 14:52:30 +00002518// This case will create two windows and one mirrored window on the default display and mirror
2519// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2520// the windows info of second display before default display.
2521TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2522 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2523 sp<FakeWindowHandle> firstWindowInPrimary =
2524 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2525 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002526 sp<FakeWindowHandle> secondWindowInPrimary =
2527 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2528 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002529
2530 sp<FakeWindowHandle> mirrorWindowInPrimary =
2531 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2532 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002533
2534 sp<FakeWindowHandle> firstWindowInSecondary =
2535 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2536 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002537
2538 sp<FakeWindowHandle> secondWindowInSecondary =
2539 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2540 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002541
2542 // Update window info, let it find window handle of second display first.
2543 mDispatcher->setInputWindows(
2544 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2545 {ADISPLAY_ID_DEFAULT,
2546 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2547
2548 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2549 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2550 {50, 50}))
2551 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2552
2553 // Window should receive motion event.
2554 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2555
2556 // Transfer touch focus
2557 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2558 secondWindowInPrimary->getToken()));
2559 // The first window gets cancel.
2560 firstWindowInPrimary->consumeMotionCancel();
2561 secondWindowInPrimary->consumeMotionDown();
2562
2563 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2564 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2565 ADISPLAY_ID_DEFAULT, {150, 50}))
2566 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2567 firstWindowInPrimary->assertNoEvents();
2568 secondWindowInPrimary->consumeMotionMove();
2569
2570 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2571 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2572 {150, 50}))
2573 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2574 firstWindowInPrimary->assertNoEvents();
2575 secondWindowInPrimary->consumeMotionUp();
2576}
2577
2578// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2579// 'transferTouch' api.
2580TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2581 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2582 sp<FakeWindowHandle> firstWindowInPrimary =
2583 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2584 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002585 sp<FakeWindowHandle> secondWindowInPrimary =
2586 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2587 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002588
2589 sp<FakeWindowHandle> mirrorWindowInPrimary =
2590 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2591 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002592
2593 sp<FakeWindowHandle> firstWindowInSecondary =
2594 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2595 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002596
2597 sp<FakeWindowHandle> secondWindowInSecondary =
2598 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2599 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002600
2601 // Update window info, let it find window handle of second display first.
2602 mDispatcher->setInputWindows(
2603 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2604 {ADISPLAY_ID_DEFAULT,
2605 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2606
2607 // Touch on second display.
2608 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2609 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2610 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2611
2612 // Window should receive motion event.
2613 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2614
2615 // Transfer touch focus
2616 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2617
2618 // The first window gets cancel.
2619 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2620 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2621
2622 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2623 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2624 SECOND_DISPLAY_ID, {150, 50}))
2625 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2626 firstWindowInPrimary->assertNoEvents();
2627 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2628
2629 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2630 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2631 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2632 firstWindowInPrimary->assertNoEvents();
2633 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2634}
2635
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002636TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002637 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002638 sp<FakeWindowHandle> window =
2639 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2640
Vishnu Nair47074b82020-08-14 11:54:47 -07002641 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002642 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002643 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002644
2645 window->consumeFocusEvent(true);
2646
2647 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2648 mDispatcher->notifyKey(&keyArgs);
2649
2650 // Window should receive key down event.
2651 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2652}
2653
2654TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002655 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002656 sp<FakeWindowHandle> window =
2657 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2658
Arthur Hung72d8dc32020-03-28 00:48:39 +00002659 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002660
2661 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2662 mDispatcher->notifyKey(&keyArgs);
2663 mDispatcher->waitForIdle();
2664
2665 window->assertNoEvents();
2666}
2667
2668// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2669TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002670 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002671 sp<FakeWindowHandle> window =
2672 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2673
Arthur Hung72d8dc32020-03-28 00:48:39 +00002674 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002675
2676 // Send key
2677 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2678 mDispatcher->notifyKey(&keyArgs);
2679 // Send motion
2680 NotifyMotionArgs motionArgs =
2681 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2682 ADISPLAY_ID_DEFAULT);
2683 mDispatcher->notifyMotion(&motionArgs);
2684
2685 // Window should receive only the motion event
2686 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2687 window->assertNoEvents(); // Key event or focus event will not be received
2688}
2689
arthurhungea3f4fc2020-12-21 23:18:53 +08002690TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2691 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2692
arthurhungea3f4fc2020-12-21 23:18:53 +08002693 sp<FakeWindowHandle> firstWindow =
2694 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2695 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08002696
arthurhungea3f4fc2020-12-21 23:18:53 +08002697 sp<FakeWindowHandle> secondWindow =
2698 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2699 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08002700
2701 // Add the windows to the dispatcher
2702 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2703
2704 PointF pointInFirst = {300, 200};
2705 PointF pointInSecond = {300, 600};
2706
2707 // Send down to the first window
2708 NotifyMotionArgs firstDownMotionArgs =
2709 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2710 ADISPLAY_ID_DEFAULT, {pointInFirst});
2711 mDispatcher->notifyMotion(&firstDownMotionArgs);
2712 // Only the first window should get the down event
2713 firstWindow->consumeMotionDown();
2714 secondWindow->assertNoEvents();
2715
2716 // Send down to the second window
2717 NotifyMotionArgs secondDownMotionArgs =
2718 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2719 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2720 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2721 {pointInFirst, pointInSecond});
2722 mDispatcher->notifyMotion(&secondDownMotionArgs);
2723 // The first window gets a move and the second a down
2724 firstWindow->consumeMotionMove();
2725 secondWindow->consumeMotionDown();
2726
2727 // Send pointer cancel to the second window
2728 NotifyMotionArgs pointerUpMotionArgs =
2729 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2730 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2731 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2732 {pointInFirst, pointInSecond});
2733 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2734 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2735 // The first window gets move and the second gets cancel.
2736 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2737 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2738
2739 // Send up event.
2740 NotifyMotionArgs upMotionArgs =
2741 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2742 ADISPLAY_ID_DEFAULT);
2743 mDispatcher->notifyMotion(&upMotionArgs);
2744 // The first window gets up and the second gets nothing.
2745 firstWindow->consumeMotionUp();
2746 secondWindow->assertNoEvents();
2747}
2748
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002749TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2750 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2751
2752 sp<FakeWindowHandle> window =
2753 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2754 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2755 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2756 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2757 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2758
2759 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2760 window->assertNoEvents();
2761 mDispatcher->waitForIdle();
2762}
2763
chaviwd1c23182019-12-20 18:44:56 -08002764class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002765public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002766 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002767 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07002768 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002769 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002770 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002771 }
2772
chaviwd1c23182019-12-20 18:44:56 -08002773 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2774
2775 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2776 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2777 expectedDisplayId, expectedFlags);
2778 }
2779
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002780 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2781
2782 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2783
chaviwd1c23182019-12-20 18:44:56 -08002784 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2785 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2786 expectedDisplayId, expectedFlags);
2787 }
2788
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002789 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2790 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2791 expectedDisplayId, expectedFlags);
2792 }
2793
chaviwd1c23182019-12-20 18:44:56 -08002794 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2795 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2796 expectedDisplayId, expectedFlags);
2797 }
2798
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002799 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2800 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2801 expectedDisplayId, expectedFlags);
2802 }
2803
Arthur Hungfbfa5722021-11-16 02:45:54 +00002804 void consumeMotionPointerDown(int32_t pointerIdx) {
2805 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2806 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2807 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2808 0 /*expectedFlags*/);
2809 }
2810
Evan Rosky84f07f02021-04-16 10:42:42 -07002811 MotionEvent* consumeMotion() {
2812 InputEvent* event = mInputReceiver->consume();
2813 if (!event) {
2814 ADD_FAILURE() << "No event was produced";
2815 return nullptr;
2816 }
2817 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2818 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2819 return nullptr;
2820 }
2821 return static_cast<MotionEvent*>(event);
2822 }
2823
chaviwd1c23182019-12-20 18:44:56 -08002824 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2825
2826private:
2827 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002828};
2829
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002830using InputDispatcherMonitorTest = InputDispatcherTest;
2831
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002832/**
2833 * Two entities that receive touch: A window, and a global monitor.
2834 * The touch goes to the window, and then the window disappears.
2835 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2836 * for the monitor, as well.
2837 * 1. foregroundWindow
2838 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2839 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002840TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002841 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2842 sp<FakeWindowHandle> window =
2843 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2844
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002845 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002846
2847 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2848 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2849 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2850 {100, 200}))
2851 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2852
2853 // Both the foreground window and the global monitor should receive the touch down
2854 window->consumeMotionDown();
2855 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2856
2857 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2858 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2859 ADISPLAY_ID_DEFAULT, {110, 200}))
2860 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2861
2862 window->consumeMotionMove();
2863 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2864
2865 // Now the foreground window goes away
2866 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2867 window->consumeMotionCancel();
2868 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2869
2870 // If more events come in, there will be no more foreground window to send them to. This will
2871 // cause a cancel for the monitor, as well.
2872 ASSERT_EQ(InputEventInjectionResult::FAILED,
2873 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2874 ADISPLAY_ID_DEFAULT, {120, 200}))
2875 << "Injection should fail because the window was removed";
2876 window->assertNoEvents();
2877 // Global monitor now gets the cancel
2878 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2879}
2880
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002881TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002882 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002883 sp<FakeWindowHandle> window =
2884 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002885 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002886
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002887 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002888
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002889 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002890 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002891 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002892 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002893 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002894}
2895
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002896TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
2897 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002898
Chris Yea209fde2020-07-22 13:54:51 -07002899 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002900 sp<FakeWindowHandle> window =
2901 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002902 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002903
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002904 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002905 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002906 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002907 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002908 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002909
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002910 // Pilfer pointers from the monitor.
2911 // This should not do anything and the window should continue to receive events.
2912 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00002913
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002914 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002915 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2916 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002917 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002918
2919 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2920 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002921}
2922
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002923TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07002924 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2925 sp<FakeWindowHandle> window =
2926 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2927 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2928 window->setWindowOffset(20, 40);
2929 window->setWindowTransform(0, 1, -1, 0);
2930
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002931 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07002932
2933 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2934 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2935 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2936 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2937 MotionEvent* event = monitor.consumeMotion();
2938 // Even though window has transform, gesture monitor must not.
2939 ASSERT_EQ(ui::Transform(), event->getTransform());
2940}
2941
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002942TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002943 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002944 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00002945
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002946 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00002947 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002948 << "Injection should fail if there is a monitor, but no touchable window";
2949 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00002950}
2951
chaviw81e2bb92019-12-18 15:03:51 -08002952TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002953 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002954 sp<FakeWindowHandle> window =
2955 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2956
Arthur Hung72d8dc32020-03-28 00:48:39 +00002957 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002958
2959 NotifyMotionArgs motionArgs =
2960 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2961 ADISPLAY_ID_DEFAULT);
2962
2963 mDispatcher->notifyMotion(&motionArgs);
2964 // Window should receive motion down event.
2965 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2966
2967 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002968 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002969 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2970 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2971 motionArgs.pointerCoords[0].getX() - 10);
2972
2973 mDispatcher->notifyMotion(&motionArgs);
2974 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2975 0 /*expectedFlags*/);
2976}
2977
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002978/**
2979 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2980 * the device default right away. In the test scenario, we check both the default value,
2981 * and the action of enabling / disabling.
2982 */
2983TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002984 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002985 sp<FakeWindowHandle> window =
2986 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08002987 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002988
2989 // Set focused application.
2990 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07002991 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002992
2993 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00002994 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002995 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002996 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
2997
2998 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07002999 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003000 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003001 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3002
3003 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003004 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3005 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003006 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003007 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003008 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003009 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003010 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3011
3012 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003013 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003014 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003015 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3016
3017 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003018 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3019 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003020 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003021 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003022 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003023 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003024 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3025
3026 window->assertNoEvents();
3027}
3028
Gang Wange9087892020-01-07 12:17:14 -05003029TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003030 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003031 sp<FakeWindowHandle> window =
3032 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3033
3034 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003035 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003036
Arthur Hung72d8dc32020-03-28 00:48:39 +00003037 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003038 setFocusedWindow(window);
3039
Gang Wange9087892020-01-07 12:17:14 -05003040 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3041
3042 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3043 mDispatcher->notifyKey(&keyArgs);
3044
3045 InputEvent* event = window->consume();
3046 ASSERT_NE(event, nullptr);
3047
3048 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3049 ASSERT_NE(verified, nullptr);
3050 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3051
3052 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3053 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3054 ASSERT_EQ(keyArgs.source, verified->source);
3055 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3056
3057 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3058
3059 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003060 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003061 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003062 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3063 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3064 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3065 ASSERT_EQ(0, verifiedKey.repeatCount);
3066}
3067
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003068TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003069 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003070 sp<FakeWindowHandle> window =
3071 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3072
3073 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3074
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003075 ui::Transform transform;
3076 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3077
3078 gui::DisplayInfo displayInfo;
3079 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3080 displayInfo.transform = transform;
3081
3082 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003083
3084 NotifyMotionArgs motionArgs =
3085 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3086 ADISPLAY_ID_DEFAULT);
3087 mDispatcher->notifyMotion(&motionArgs);
3088
3089 InputEvent* event = window->consume();
3090 ASSERT_NE(event, nullptr);
3091
3092 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3093 ASSERT_NE(verified, nullptr);
3094 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3095
3096 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3097 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3098 EXPECT_EQ(motionArgs.source, verified->source);
3099 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3100
3101 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3102
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003103 const vec2 rawXY =
3104 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3105 motionArgs.pointerCoords[0].getXYValue());
3106 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3107 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003108 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003109 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003110 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003111 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3112 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3113}
3114
chaviw09c8d2d2020-08-24 15:48:26 -07003115/**
3116 * Ensure that separate calls to sign the same data are generating the same key.
3117 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3118 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3119 * tests.
3120 */
3121TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3122 KeyEvent event = getTestKeyEvent();
3123 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3124
3125 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3126 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3127 ASSERT_EQ(hmac1, hmac2);
3128}
3129
3130/**
3131 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3132 */
3133TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3134 KeyEvent event = getTestKeyEvent();
3135 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3136 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3137
3138 verifiedEvent.deviceId += 1;
3139 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3140
3141 verifiedEvent.source += 1;
3142 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3143
3144 verifiedEvent.eventTimeNanos += 1;
3145 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3146
3147 verifiedEvent.displayId += 1;
3148 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3149
3150 verifiedEvent.action += 1;
3151 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3152
3153 verifiedEvent.downTimeNanos += 1;
3154 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3155
3156 verifiedEvent.flags += 1;
3157 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3158
3159 verifiedEvent.keyCode += 1;
3160 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3161
3162 verifiedEvent.scanCode += 1;
3163 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3164
3165 verifiedEvent.metaState += 1;
3166 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3167
3168 verifiedEvent.repeatCount += 1;
3169 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3170}
3171
Vishnu Nair958da932020-08-21 17:12:37 -07003172TEST_F(InputDispatcherTest, SetFocusedWindow) {
3173 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3174 sp<FakeWindowHandle> windowTop =
3175 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3176 sp<FakeWindowHandle> windowSecond =
3177 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3178 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3179
3180 // Top window is also focusable but is not granted focus.
3181 windowTop->setFocusable(true);
3182 windowSecond->setFocusable(true);
3183 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3184 setFocusedWindow(windowSecond);
3185
3186 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003187 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3188 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003189
3190 // Focused window should receive event.
3191 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3192 windowTop->assertNoEvents();
3193}
3194
3195TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3196 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3197 sp<FakeWindowHandle> window =
3198 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3199 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3200
3201 window->setFocusable(true);
3202 // Release channel for window is no longer valid.
3203 window->releaseChannel();
3204 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3205 setFocusedWindow(window);
3206
3207 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003208 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3209 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003210
3211 // window channel is invalid, so it should not receive any input event.
3212 window->assertNoEvents();
3213}
3214
3215TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3216 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3217 sp<FakeWindowHandle> window =
3218 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003219 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003220 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3221
Vishnu Nair958da932020-08-21 17:12:37 -07003222 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3223 setFocusedWindow(window);
3224
3225 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003226 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3227 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003228
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003229 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003230 window->assertNoEvents();
3231}
3232
3233TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3234 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3235 sp<FakeWindowHandle> windowTop =
3236 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3237 sp<FakeWindowHandle> windowSecond =
3238 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3239 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3240
3241 windowTop->setFocusable(true);
3242 windowSecond->setFocusable(true);
3243 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3244 setFocusedWindow(windowTop);
3245 windowTop->consumeFocusEvent(true);
3246
3247 setFocusedWindow(windowSecond, windowTop);
3248 windowSecond->consumeFocusEvent(true);
3249 windowTop->consumeFocusEvent(false);
3250
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003251 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3252 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003253
3254 // Focused window should receive event.
3255 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3256}
3257
3258TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3259 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3260 sp<FakeWindowHandle> windowTop =
3261 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3262 sp<FakeWindowHandle> windowSecond =
3263 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3264 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3265
3266 windowTop->setFocusable(true);
3267 windowSecond->setFocusable(true);
3268 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3269 setFocusedWindow(windowSecond, windowTop);
3270
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003271 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3272 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003273
3274 // Event should be dropped.
3275 windowTop->assertNoEvents();
3276 windowSecond->assertNoEvents();
3277}
3278
3279TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3280 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3281 sp<FakeWindowHandle> window =
3282 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3283 sp<FakeWindowHandle> previousFocusedWindow =
3284 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3285 ADISPLAY_ID_DEFAULT);
3286 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3287
3288 window->setFocusable(true);
3289 previousFocusedWindow->setFocusable(true);
3290 window->setVisible(false);
3291 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3292 setFocusedWindow(previousFocusedWindow);
3293 previousFocusedWindow->consumeFocusEvent(true);
3294
3295 // Requesting focus on invisible window takes focus from currently focused window.
3296 setFocusedWindow(window);
3297 previousFocusedWindow->consumeFocusEvent(false);
3298
3299 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003300 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003301 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003302 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003303
3304 // Window does not get focus event or key down.
3305 window->assertNoEvents();
3306
3307 // Window becomes visible.
3308 window->setVisible(true);
3309 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3310
3311 // Window receives focus event.
3312 window->consumeFocusEvent(true);
3313 // Focused window receives key down.
3314 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3315}
3316
Vishnu Nair599f1412021-06-21 10:39:58 -07003317TEST_F(InputDispatcherTest, DisplayRemoved) {
3318 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3319 sp<FakeWindowHandle> window =
3320 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3321 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3322
3323 // window is granted focus.
3324 window->setFocusable(true);
3325 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3326 setFocusedWindow(window);
3327 window->consumeFocusEvent(true);
3328
3329 // When a display is removed window loses focus.
3330 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3331 window->consumeFocusEvent(false);
3332}
3333
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003334/**
3335 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3336 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3337 * of the 'slipperyEnterWindow'.
3338 *
3339 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3340 * a way so that the touched location is no longer covered by the top window.
3341 *
3342 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3343 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3344 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3345 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3346 * with ACTION_DOWN).
3347 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3348 * window moved itself away from the touched location and had Flag::SLIPPERY.
3349 *
3350 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3351 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3352 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3353 *
3354 * In this test, we ensure that the event received by the bottom window has
3355 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3356 */
3357TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3358 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3359 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3360
3361 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3362 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3363
3364 sp<FakeWindowHandle> slipperyExitWindow =
3365 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003366 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003367 // Make sure this one overlaps the bottom window
3368 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3369 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3370 // one. Windows with the same owner are not considered to be occluding each other.
3371 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3372
3373 sp<FakeWindowHandle> slipperyEnterWindow =
3374 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3375 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3376
3377 mDispatcher->setInputWindows(
3378 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3379
3380 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3381 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3382 ADISPLAY_ID_DEFAULT, {{50, 50}});
3383 mDispatcher->notifyMotion(&args);
3384 slipperyExitWindow->consumeMotionDown();
3385 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3386 mDispatcher->setInputWindows(
3387 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3388
3389 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3390 ADISPLAY_ID_DEFAULT, {{51, 51}});
3391 mDispatcher->notifyMotion(&args);
3392
3393 slipperyExitWindow->consumeMotionCancel();
3394
3395 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3396 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3397}
3398
Garfield Tan1c7bc862020-01-28 13:24:04 -08003399class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3400protected:
3401 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3402 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3403
Chris Yea209fde2020-07-22 13:54:51 -07003404 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003405 sp<FakeWindowHandle> mWindow;
3406
3407 virtual void SetUp() override {
3408 mFakePolicy = new FakeInputDispatcherPolicy();
3409 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003410 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003411 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3412 ASSERT_EQ(OK, mDispatcher->start());
3413
3414 setUpWindow();
3415 }
3416
3417 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003418 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003419 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3420
Vishnu Nair47074b82020-08-14 11:54:47 -07003421 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003422 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003423 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003424 mWindow->consumeFocusEvent(true);
3425 }
3426
Chris Ye2ad95392020-09-01 13:44:44 -07003427 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003428 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003429 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003430 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3431 mDispatcher->notifyKey(&keyArgs);
3432
3433 // Window should receive key down event.
3434 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3435 }
3436
3437 void expectKeyRepeatOnce(int32_t repeatCount) {
3438 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3439 InputEvent* repeatEvent = mWindow->consume();
3440 ASSERT_NE(nullptr, repeatEvent);
3441
3442 uint32_t eventType = repeatEvent->getType();
3443 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3444
3445 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3446 uint32_t eventAction = repeatKeyEvent->getAction();
3447 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3448 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3449 }
3450
Chris Ye2ad95392020-09-01 13:44:44 -07003451 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003452 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003453 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003454 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3455 mDispatcher->notifyKey(&keyArgs);
3456
3457 // Window should receive key down event.
3458 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3459 0 /*expectedFlags*/);
3460 }
3461};
3462
3463TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003464 sendAndConsumeKeyDown(1 /* deviceId */);
3465 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3466 expectKeyRepeatOnce(repeatCount);
3467 }
3468}
3469
3470TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3471 sendAndConsumeKeyDown(1 /* deviceId */);
3472 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3473 expectKeyRepeatOnce(repeatCount);
3474 }
3475 sendAndConsumeKeyDown(2 /* deviceId */);
3476 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003477 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3478 expectKeyRepeatOnce(repeatCount);
3479 }
3480}
3481
3482TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003483 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003484 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003485 sendAndConsumeKeyUp(1 /* deviceId */);
3486 mWindow->assertNoEvents();
3487}
3488
3489TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3490 sendAndConsumeKeyDown(1 /* deviceId */);
3491 expectKeyRepeatOnce(1 /*repeatCount*/);
3492 sendAndConsumeKeyDown(2 /* deviceId */);
3493 expectKeyRepeatOnce(1 /*repeatCount*/);
3494 // Stale key up from device 1.
3495 sendAndConsumeKeyUp(1 /* deviceId */);
3496 // Device 2 is still down, keep repeating
3497 expectKeyRepeatOnce(2 /*repeatCount*/);
3498 expectKeyRepeatOnce(3 /*repeatCount*/);
3499 // Device 2 key up
3500 sendAndConsumeKeyUp(2 /* deviceId */);
3501 mWindow->assertNoEvents();
3502}
3503
3504TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3505 sendAndConsumeKeyDown(1 /* deviceId */);
3506 expectKeyRepeatOnce(1 /*repeatCount*/);
3507 sendAndConsumeKeyDown(2 /* deviceId */);
3508 expectKeyRepeatOnce(1 /*repeatCount*/);
3509 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3510 sendAndConsumeKeyUp(2 /* deviceId */);
3511 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003512 mWindow->assertNoEvents();
3513}
3514
liushenxiang42232912021-05-21 20:24:09 +08003515TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3516 sendAndConsumeKeyDown(DEVICE_ID);
3517 expectKeyRepeatOnce(1 /*repeatCount*/);
3518 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3519 mDispatcher->notifyDeviceReset(&args);
3520 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3521 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3522 mWindow->assertNoEvents();
3523}
3524
Garfield Tan1c7bc862020-01-28 13:24:04 -08003525TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003526 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003527 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3528 InputEvent* repeatEvent = mWindow->consume();
3529 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3530 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3531 IdGenerator::getSource(repeatEvent->getId()));
3532 }
3533}
3534
3535TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003536 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003537
3538 std::unordered_set<int32_t> idSet;
3539 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3540 InputEvent* repeatEvent = mWindow->consume();
3541 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3542 int32_t id = repeatEvent->getId();
3543 EXPECT_EQ(idSet.end(), idSet.find(id));
3544 idSet.insert(id);
3545 }
3546}
3547
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003548/* Test InputDispatcher for MultiDisplay */
3549class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3550public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003551 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003552 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003553
Chris Yea209fde2020-07-22 13:54:51 -07003554 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003555 windowInPrimary =
3556 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003557
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003558 // Set focus window for primary display, but focused display would be second one.
3559 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003560 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003561 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003562 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003563 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003564
Chris Yea209fde2020-07-22 13:54:51 -07003565 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003566 windowInSecondary =
3567 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003568 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003569 // Set focus display to second one.
3570 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3571 // Set focus window for second display.
3572 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003573 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003574 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003575 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003576 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003577 }
3578
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003579 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003580 InputDispatcherTest::TearDown();
3581
Chris Yea209fde2020-07-22 13:54:51 -07003582 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003583 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003584 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003585 windowInSecondary.clear();
3586 }
3587
3588protected:
Chris Yea209fde2020-07-22 13:54:51 -07003589 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003590 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003591 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003592 sp<FakeWindowHandle> windowInSecondary;
3593};
3594
3595TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3596 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003597 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3598 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3599 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003600 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003601 windowInSecondary->assertNoEvents();
3602
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003603 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003604 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3605 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3606 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003607 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003608 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003609}
3610
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003611TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003612 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003613 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3614 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003615 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003616 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003617 windowInSecondary->assertNoEvents();
3618
3619 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003620 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003621 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003622 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003623 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003624
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003625 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003626 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003627
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003628 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003629 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3630 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003631
3632 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003633 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003634 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003635 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003636 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003637 windowInSecondary->assertNoEvents();
3638}
3639
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003640// Test per-display input monitors for motion event.
3641TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003642 FakeMonitorReceiver monitorInPrimary =
3643 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3644 FakeMonitorReceiver monitorInSecondary =
3645 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003646
3647 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003648 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3649 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3650 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003651 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003652 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003653 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003654 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003655
3656 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003657 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3658 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3659 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003660 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003661 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003662 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003663 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003664
3665 // Test inject a non-pointer motion event.
3666 // If specific a display, it will dispatch to the focused window of particular display,
3667 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003668 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3669 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3670 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003671 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003672 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003673 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003674 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003675}
3676
3677// Test per-display input monitors for key event.
3678TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003679 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003680 FakeMonitorReceiver monitorInPrimary =
3681 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3682 FakeMonitorReceiver monitorInSecondary =
3683 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003684
3685 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003686 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3687 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003688 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003689 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003690 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003691 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003692}
3693
Vishnu Nair958da932020-08-21 17:12:37 -07003694TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3695 sp<FakeWindowHandle> secondWindowInPrimary =
3696 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3697 secondWindowInPrimary->setFocusable(true);
3698 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3699 setFocusedWindow(secondWindowInPrimary);
3700 windowInPrimary->consumeFocusEvent(false);
3701 secondWindowInPrimary->consumeFocusEvent(true);
3702
3703 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003704 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3705 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003706 windowInPrimary->assertNoEvents();
3707 windowInSecondary->assertNoEvents();
3708 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3709}
3710
Arthur Hungdfd528e2021-12-08 13:23:04 +00003711TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3712 FakeMonitorReceiver monitorInPrimary =
3713 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3714 FakeMonitorReceiver monitorInSecondary =
3715 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3716
3717 // Test touch down on primary display.
3718 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3719 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3720 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3721 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3722 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3723
3724 // Test touch down on second display.
3725 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3726 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3727 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3728 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3729 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3730
3731 // Trigger cancel touch.
3732 mDispatcher->cancelCurrentTouch();
3733 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3734 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3735 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3736 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3737
3738 // Test inject a move motion event, no window/monitor should receive the event.
3739 ASSERT_EQ(InputEventInjectionResult::FAILED,
3740 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3741 ADISPLAY_ID_DEFAULT, {110, 200}))
3742 << "Inject motion event should return InputEventInjectionResult::FAILED";
3743 windowInPrimary->assertNoEvents();
3744 monitorInPrimary.assertNoEvents();
3745
3746 ASSERT_EQ(InputEventInjectionResult::FAILED,
3747 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3748 SECOND_DISPLAY_ID, {110, 200}))
3749 << "Inject motion event should return InputEventInjectionResult::FAILED";
3750 windowInSecondary->assertNoEvents();
3751 monitorInSecondary.assertNoEvents();
3752}
3753
Jackal Guof9696682018-10-05 12:23:23 +08003754class InputFilterTest : public InputDispatcherTest {
3755protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003756 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3757 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003758 NotifyMotionArgs motionArgs;
3759
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003760 motionArgs =
3761 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003762 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003763 motionArgs =
3764 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003765 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003766 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003767 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003768 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3769 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003770 } else {
3771 mFakePolicy->assertFilterInputEventWasNotCalled();
3772 }
3773 }
3774
3775 void testNotifyKey(bool expectToBeFiltered) {
3776 NotifyKeyArgs keyArgs;
3777
3778 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3779 mDispatcher->notifyKey(&keyArgs);
3780 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3781 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003782 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003783
3784 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003785 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003786 } else {
3787 mFakePolicy->assertFilterInputEventWasNotCalled();
3788 }
3789 }
3790};
3791
3792// Test InputFilter for MotionEvent
3793TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3794 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3795 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3796 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3797
3798 // Enable InputFilter
3799 mDispatcher->setInputFilterEnabled(true);
3800 // Test touch on both primary and second display, and check if both events are filtered.
3801 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3802 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3803
3804 // Disable InputFilter
3805 mDispatcher->setInputFilterEnabled(false);
3806 // Test touch on both primary and second display, and check if both events aren't filtered.
3807 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3808 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3809}
3810
3811// Test InputFilter for KeyEvent
3812TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3813 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3814 testNotifyKey(/*expectToBeFiltered*/ false);
3815
3816 // Enable InputFilter
3817 mDispatcher->setInputFilterEnabled(true);
3818 // Send a key event, and check if it is filtered.
3819 testNotifyKey(/*expectToBeFiltered*/ true);
3820
3821 // Disable InputFilter
3822 mDispatcher->setInputFilterEnabled(false);
3823 // Send a key event, and check if it isn't filtered.
3824 testNotifyKey(/*expectToBeFiltered*/ false);
3825}
3826
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003827// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3828// logical display coordinate space.
3829TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3830 ui::Transform firstDisplayTransform;
3831 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3832 ui::Transform secondDisplayTransform;
3833 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3834
3835 std::vector<gui::DisplayInfo> displayInfos(2);
3836 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3837 displayInfos[0].transform = firstDisplayTransform;
3838 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3839 displayInfos[1].transform = secondDisplayTransform;
3840
3841 mDispatcher->onWindowInfosChanged({}, displayInfos);
3842
3843 // Enable InputFilter
3844 mDispatcher->setInputFilterEnabled(true);
3845
3846 // Ensure the correct transforms are used for the displays.
3847 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3848 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3849}
3850
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003851class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3852protected:
3853 virtual void SetUp() override {
3854 InputDispatcherTest::SetUp();
3855
3856 /**
3857 * We don't need to enable input filter to test the injected event policy, but we enabled it
3858 * here to make the tests more realistic, since this policy only matters when inputfilter is
3859 * on.
3860 */
3861 mDispatcher->setInputFilterEnabled(true);
3862
3863 std::shared_ptr<InputApplicationHandle> application =
3864 std::make_shared<FakeApplicationHandle>();
3865 mWindow =
3866 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3867
3868 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3869 mWindow->setFocusable(true);
3870 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3871 setFocusedWindow(mWindow);
3872 mWindow->consumeFocusEvent(true);
3873 }
3874
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003875 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3876 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003877 KeyEvent event;
3878
3879 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3880 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3881 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3882 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3883 const int32_t additionalPolicyFlags =
3884 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3885 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3886 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3887 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3888 policyFlags | additionalPolicyFlags));
3889
3890 InputEvent* received = mWindow->consume();
3891 ASSERT_NE(nullptr, received);
3892 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003893 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3894 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3895 ASSERT_EQ(flags, keyEvent.getFlags());
3896 }
3897
3898 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3899 int32_t flags) {
3900 MotionEvent event;
3901 PointerProperties pointerProperties[1];
3902 PointerCoords pointerCoords[1];
3903 pointerProperties[0].clear();
3904 pointerProperties[0].id = 0;
3905 pointerCoords[0].clear();
3906 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3907 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3908
3909 ui::Transform identityTransform;
3910 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3911 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3912 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3913 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3914 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003915 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003916 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003917 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3918
3919 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3920 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3921 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3922 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3923 policyFlags | additionalPolicyFlags));
3924
3925 InputEvent* received = mWindow->consume();
3926 ASSERT_NE(nullptr, received);
3927 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3928 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3929 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3930 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003931 }
3932
3933private:
3934 sp<FakeWindowHandle> mWindow;
3935};
3936
3937TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003938 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3939 // filter. Without it, the event will no different from a regularly injected event, and the
3940 // injected device id will be overwritten.
3941 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3942 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003943}
3944
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003945TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003946 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003947 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3948 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3949}
3950
3951TEST_F(InputFilterInjectionPolicyTest,
3952 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3953 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3954 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3955 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003956}
3957
3958TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3959 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003960 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003961}
3962
chaviwfd6d3512019-03-25 13:23:49 -07003963class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003964 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003965 InputDispatcherTest::SetUp();
3966
Chris Yea209fde2020-07-22 13:54:51 -07003967 std::shared_ptr<FakeApplicationHandle> application =
3968 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003969 mUnfocusedWindow =
3970 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003971 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07003972
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003973 mFocusedWindow =
3974 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3975 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07003976
3977 // Set focused application.
3978 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003979 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003980
3981 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003982 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003983 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003984 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07003985 }
3986
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003987 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07003988 InputDispatcherTest::TearDown();
3989
3990 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003991 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07003992 }
3993
3994protected:
3995 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003996 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07003997 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07003998};
3999
4000// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4001// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4002// the onPointerDownOutsideFocus callback.
4003TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004004 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004005 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4006 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004007 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004008 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004009
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004010 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004011 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4012}
4013
4014// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4015// DOWN on the window that doesn't have focus. Ensure no window received the
4016// onPointerDownOutsideFocus callback.
4017TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004018 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004019 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004020 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004021 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004022
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004023 ASSERT_TRUE(mDispatcher->waitForIdle());
4024 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004025}
4026
4027// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4028// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4029TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004030 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4031 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004032 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004033 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004034
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004035 ASSERT_TRUE(mDispatcher->waitForIdle());
4036 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004037}
4038
4039// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4040// DOWN on the window that already has focus. Ensure no window received the
4041// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004042TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004043 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004044 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004045 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004046 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004047 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004048
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004049 ASSERT_TRUE(mDispatcher->waitForIdle());
4050 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004051}
4052
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004053// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4054// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4055TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4056 const MotionEvent event =
4057 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4058 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4059 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4060 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4061 .build();
4062 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4063 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4064 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4065
4066 ASSERT_TRUE(mDispatcher->waitForIdle());
4067 mFakePolicy->assertOnPointerDownWasNotCalled();
4068 // Ensure that the unfocused window did not receive any FOCUS events.
4069 mUnfocusedWindow->assertNoEvents();
4070}
4071
chaviwaf87b3e2019-10-01 16:59:28 -07004072// These tests ensures we can send touch events to a single client when there are multiple input
4073// windows that point to the same client token.
4074class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4075 virtual void SetUp() override {
4076 InputDispatcherTest::SetUp();
4077
Chris Yea209fde2020-07-22 13:54:51 -07004078 std::shared_ptr<FakeApplicationHandle> application =
4079 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004080 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4081 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004082 mWindow1->setFrame(Rect(0, 0, 100, 100));
4083
4084 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4085 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004086 mWindow2->setFrame(Rect(100, 100, 200, 200));
4087
Arthur Hung72d8dc32020-03-28 00:48:39 +00004088 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004089 }
4090
4091protected:
4092 sp<FakeWindowHandle> mWindow1;
4093 sp<FakeWindowHandle> mWindow2;
4094
4095 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004096 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004097 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4098 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004099 }
4100
4101 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4102 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004103 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004104 InputEvent* event = window->consume();
4105
4106 ASSERT_NE(nullptr, event) << name.c_str()
4107 << ": consumer should have returned non-NULL event.";
4108
4109 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4110 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4111 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4112
4113 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004114 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004115
4116 for (size_t i = 0; i < points.size(); i++) {
4117 float expectedX = points[i].x;
4118 float expectedY = points[i].y;
4119
4120 EXPECT_EQ(expectedX, motionEvent.getX(i))
4121 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4122 << ", got " << motionEvent.getX(i);
4123 EXPECT_EQ(expectedY, motionEvent.getY(i))
4124 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4125 << ", got " << motionEvent.getY(i);
4126 }
4127 }
chaviw9eaa22c2020-07-01 16:21:27 -07004128
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004129 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004130 std::vector<PointF> expectedPoints) {
4131 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4132 ADISPLAY_ID_DEFAULT, touchedPoints);
4133 mDispatcher->notifyMotion(&motionArgs);
4134
4135 // Always consume from window1 since it's the window that has the InputReceiver
4136 consumeMotionEvent(mWindow1, action, expectedPoints);
4137 }
chaviwaf87b3e2019-10-01 16:59:28 -07004138};
4139
4140TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4141 // Touch Window 1
4142 PointF touchedPoint = {10, 10};
4143 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004144 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004145
4146 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004147 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004148
4149 // Touch Window 2
4150 touchedPoint = {150, 150};
4151 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004152 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004153}
4154
chaviw9eaa22c2020-07-01 16:21:27 -07004155TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4156 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004157 mWindow2->setWindowScale(0.5f, 0.5f);
4158
4159 // Touch Window 1
4160 PointF touchedPoint = {10, 10};
4161 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004162 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004163 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004164 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004165
4166 // Touch Window 2
4167 touchedPoint = {150, 150};
4168 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004169 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4170 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004171
chaviw9eaa22c2020-07-01 16:21:27 -07004172 // Update the transform so rotation is set
4173 mWindow2->setWindowTransform(0, -1, 1, 0);
4174 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4175 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004176}
4177
chaviw9eaa22c2020-07-01 16:21:27 -07004178TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004179 mWindow2->setWindowScale(0.5f, 0.5f);
4180
4181 // Touch Window 1
4182 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4183 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004184 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004185
4186 // Touch Window 2
4187 int32_t actionPointerDown =
4188 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004189 touchedPoints.push_back(PointF{150, 150});
4190 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4191 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004192
chaviw9eaa22c2020-07-01 16:21:27 -07004193 // Release Window 2
4194 int32_t actionPointerUp =
4195 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4196 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4197 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004198
chaviw9eaa22c2020-07-01 16:21:27 -07004199 // Update the transform so rotation is set for Window 2
4200 mWindow2->setWindowTransform(0, -1, 1, 0);
4201 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4202 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004203}
4204
chaviw9eaa22c2020-07-01 16:21:27 -07004205TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004206 mWindow2->setWindowScale(0.5f, 0.5f);
4207
4208 // Touch Window 1
4209 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4210 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004211 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004212
4213 // Touch Window 2
4214 int32_t actionPointerDown =
4215 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004216 touchedPoints.push_back(PointF{150, 150});
4217 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004218
chaviw9eaa22c2020-07-01 16:21:27 -07004219 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004220
4221 // Move both windows
4222 touchedPoints = {{20, 20}, {175, 175}};
4223 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4224 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4225
chaviw9eaa22c2020-07-01 16:21:27 -07004226 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004227
chaviw9eaa22c2020-07-01 16:21:27 -07004228 // Release Window 2
4229 int32_t actionPointerUp =
4230 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4231 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4232 expectedPoints.pop_back();
4233
4234 // Touch Window 2
4235 mWindow2->setWindowTransform(0, -1, 1, 0);
4236 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4237 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4238
4239 // Move both windows
4240 touchedPoints = {{20, 20}, {175, 175}};
4241 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4242 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4243
4244 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004245}
4246
4247TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4248 mWindow1->setWindowScale(0.5f, 0.5f);
4249
4250 // Touch Window 1
4251 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4252 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004253 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004254
4255 // Touch Window 2
4256 int32_t actionPointerDown =
4257 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004258 touchedPoints.push_back(PointF{150, 150});
4259 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004260
chaviw9eaa22c2020-07-01 16:21:27 -07004261 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004262
4263 // Move both windows
4264 touchedPoints = {{20, 20}, {175, 175}};
4265 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4266 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4267
chaviw9eaa22c2020-07-01 16:21:27 -07004268 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004269}
4270
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004271class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4272 virtual void SetUp() override {
4273 InputDispatcherTest::SetUp();
4274
Chris Yea209fde2020-07-22 13:54:51 -07004275 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004276 mApplication->setDispatchingTimeout(20ms);
4277 mWindow =
4278 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4279 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004280 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004281 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004282
4283 // Set focused application.
4284 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4285
4286 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004287 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004288 mWindow->consumeFocusEvent(true);
4289 }
4290
4291 virtual void TearDown() override {
4292 InputDispatcherTest::TearDown();
4293 mWindow.clear();
4294 }
4295
4296protected:
Chris Yea209fde2020-07-22 13:54:51 -07004297 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004298 sp<FakeWindowHandle> mWindow;
4299 static constexpr PointF WINDOW_LOCATION = {20, 20};
4300
4301 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004302 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004303 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4304 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004305 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004306 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4307 WINDOW_LOCATION));
4308 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004309
4310 sp<FakeWindowHandle> addSpyWindow() {
4311 sp<FakeWindowHandle> spy =
4312 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4313 spy->setTrustedOverlay(true);
4314 spy->setFocusable(false);
4315 spy->setInputFeatures(WindowInfo::Feature::SPY);
4316 spy->setDispatchingTimeout(30ms);
4317 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4318 return spy;
4319 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004320};
4321
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004322// Send a tap and respond, which should not cause an ANR.
4323TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4324 tapOnWindow();
4325 mWindow->consumeMotionDown();
4326 mWindow->consumeMotionUp();
4327 ASSERT_TRUE(mDispatcher->waitForIdle());
4328 mFakePolicy->assertNotifyAnrWasNotCalled();
4329}
4330
4331// Send a regular key and respond, which should not cause an ANR.
4332TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004333 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004334 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4335 ASSERT_TRUE(mDispatcher->waitForIdle());
4336 mFakePolicy->assertNotifyAnrWasNotCalled();
4337}
4338
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004339TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4340 mWindow->setFocusable(false);
4341 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4342 mWindow->consumeFocusEvent(false);
4343
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004344 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004345 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004346 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4347 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004348 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004349 // Key will not go to window because we have no focused window.
4350 // The 'no focused window' ANR timer should start instead.
4351
4352 // Now, the focused application goes away.
4353 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4354 // The key should get dropped and there should be no ANR.
4355
4356 ASSERT_TRUE(mDispatcher->waitForIdle());
4357 mFakePolicy->assertNotifyAnrWasNotCalled();
4358}
4359
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004360// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004361// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4362// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004363TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004364 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004365 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4366 WINDOW_LOCATION));
4367
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004368 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4369 ASSERT_TRUE(sequenceNum);
4370 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004371 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004372
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004373 mWindow->finishEvent(*sequenceNum);
4374 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4375 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004376 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004377 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004378}
4379
4380// Send a key to the app and have the app not respond right away.
4381TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4382 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004383 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004384 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4385 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004386 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004387 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004388 ASSERT_TRUE(mDispatcher->waitForIdle());
4389}
4390
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004391// We have a focused application, but no focused window
4392TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004393 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004394 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4395 mWindow->consumeFocusEvent(false);
4396
4397 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004398 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004399 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4400 WINDOW_LOCATION));
4401 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4402 mDispatcher->waitForIdle();
4403 mFakePolicy->assertNotifyAnrWasNotCalled();
4404
4405 // Once a focused event arrives, we get an ANR for this application
4406 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4407 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004408 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004409 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004410 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004411 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004412 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004413 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004414 ASSERT_TRUE(mDispatcher->waitForIdle());
4415}
4416
4417// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004418// Make sure that we don't notify policy twice about the same ANR.
4419TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004420 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004421 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4422 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004423
4424 // Once a focused event arrives, we get an ANR for this application
4425 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4426 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004427 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004428 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004429 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004430 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004431 const std::chrono::duration appTimeout =
4432 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004433 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004434
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004435 std::this_thread::sleep_for(appTimeout);
4436 // ANR should not be raised again. It is up to policy to do that if it desires.
4437 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004438
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004439 // If we now get a focused window, the ANR should stop, but the policy handles that via
4440 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004441 ASSERT_TRUE(mDispatcher->waitForIdle());
4442}
4443
4444// We have a focused application, but no focused window
4445TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004446 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004447 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4448 mWindow->consumeFocusEvent(false);
4449
4450 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004451 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004452 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004453 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4454 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004455
4456 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004457 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004458
4459 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004460 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004461 ASSERT_TRUE(mDispatcher->waitForIdle());
4462 mWindow->assertNoEvents();
4463}
4464
4465/**
4466 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4467 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4468 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4469 * the ANR mechanism should still work.
4470 *
4471 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4472 * DOWN event, while not responding on the second one.
4473 */
4474TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4475 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4476 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4477 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4478 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4479 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004480 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004481
4482 // Now send ACTION_UP, with identical timestamp
4483 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4484 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4485 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4486 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004487 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004488
4489 // We have now sent down and up. Let's consume first event and then ANR on the second.
4490 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4491 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004492 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004493}
4494
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004495// A spy window can receive an ANR
4496TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4497 sp<FakeWindowHandle> spy = addSpyWindow();
4498
4499 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4500 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4501 WINDOW_LOCATION));
4502 mWindow->consumeMotionDown();
4503
4504 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4505 ASSERT_TRUE(sequenceNum);
4506 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4507 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy->getToken());
4508
4509 spy->finishEvent(*sequenceNum);
4510 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4511 0 /*flags*/);
4512 ASSERT_TRUE(mDispatcher->waitForIdle());
4513 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken());
4514}
4515
4516// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004517// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004518TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4519 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004520
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004521 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4522 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004523 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004524 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004525
4526 // Stuck on the ACTION_UP
4527 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004528 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004529
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004530 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004531 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004532 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4533 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004534
4535 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4536 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004537 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004538 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004539 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004540}
4541
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004542// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004543// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004544TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4545 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004546
4547 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004548 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4549 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004550
4551 mWindow->consumeMotionDown();
4552 // Stuck on the ACTION_UP
4553 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004554 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004555
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004556 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004557 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004558 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4559 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004560
4561 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4562 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004563 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004564 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004565 spy->assertNoEvents();
4566}
4567
4568TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4569 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4570
4571 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4572
4573 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4574 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4575 WINDOW_LOCATION));
4576
4577 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4578 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4579 ASSERT_TRUE(consumeSeq);
4580
4581 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(30ms);
4582
4583 monitor.finishEvent(*consumeSeq);
4584 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4585
4586 ASSERT_TRUE(mDispatcher->waitForIdle());
4587 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004588}
4589
4590// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4591// process events, you don't get an anr. When the window later becomes unresponsive again, you
4592// get an ANR again.
4593// 1. tap -> block on ACTION_UP -> receive ANR
4594// 2. consume all pending events (= queue becomes healthy again)
4595// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4596TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4597 tapOnWindow();
4598
4599 mWindow->consumeMotionDown();
4600 // Block on ACTION_UP
4601 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004602 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004603 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4604 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004605 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004606 mWindow->assertNoEvents();
4607
4608 tapOnWindow();
4609 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004610 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004611 mWindow->consumeMotionUp();
4612
4613 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004614 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004615 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004616 mWindow->assertNoEvents();
4617}
4618
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004619// If a connection remains unresponsive for a while, make sure policy is only notified once about
4620// it.
4621TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004622 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004623 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4624 WINDOW_LOCATION));
4625
4626 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004627 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004628 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004629 // 'notifyConnectionUnresponsive' should only be called once per connection
4630 mFakePolicy->assertNotifyAnrWasNotCalled();
4631 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004632 mWindow->consumeMotionDown();
4633 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4634 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4635 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004636 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004637 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004638 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004639}
4640
4641/**
4642 * If a window is processing a motion event, and then a key event comes in, the key event should
4643 * not to to the focused window until the motion is processed.
4644 *
4645 * Warning!!!
4646 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4647 * and the injection timeout that we specify when injecting the key.
4648 * We must have the injection timeout (10ms) be smaller than
4649 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4650 *
4651 * If that value changes, this test should also change.
4652 */
4653TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4654 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4655 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4656
4657 tapOnWindow();
4658 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4659 ASSERT_TRUE(downSequenceNum);
4660 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4661 ASSERT_TRUE(upSequenceNum);
4662 // Don't finish the events yet, and send a key
4663 // Injection will "succeed" because we will eventually give up and send the key to the focused
4664 // window even if motions are still being processed. But because the injection timeout is short,
4665 // we will receive INJECTION_TIMED_OUT as the result.
4666
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004667 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004668 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004669 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4670 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004671 // Key will not be sent to the window, yet, because the window is still processing events
4672 // and the key remains pending, waiting for the touch events to be processed
4673 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4674 ASSERT_FALSE(keySequenceNum);
4675
4676 std::this_thread::sleep_for(500ms);
4677 // if we wait long enough though, dispatcher will give up, and still send the key
4678 // to the focused window, even though we have not yet finished the motion event
4679 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4680 mWindow->finishEvent(*downSequenceNum);
4681 mWindow->finishEvent(*upSequenceNum);
4682}
4683
4684/**
4685 * If a window is processing a motion event, and then a key event comes in, the key event should
4686 * not go to the focused window until the motion is processed.
4687 * If then a new motion comes in, then the pending key event should be going to the currently
4688 * focused window right away.
4689 */
4690TEST_F(InputDispatcherSingleWindowAnr,
4691 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4692 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4693 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4694
4695 tapOnWindow();
4696 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4697 ASSERT_TRUE(downSequenceNum);
4698 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4699 ASSERT_TRUE(upSequenceNum);
4700 // Don't finish the events yet, and send a key
4701 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004702 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004703 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004704 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004705 // At this point, key is still pending, and should not be sent to the application yet.
4706 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4707 ASSERT_FALSE(keySequenceNum);
4708
4709 // Now tap down again. It should cause the pending key to go to the focused window right away.
4710 tapOnWindow();
4711 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4712 // the other events yet. We can finish events in any order.
4713 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4714 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4715 mWindow->consumeMotionDown();
4716 mWindow->consumeMotionUp();
4717 mWindow->assertNoEvents();
4718}
4719
4720class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4721 virtual void SetUp() override {
4722 InputDispatcherTest::SetUp();
4723
Chris Yea209fde2020-07-22 13:54:51 -07004724 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004725 mApplication->setDispatchingTimeout(10ms);
4726 mUnfocusedWindow =
4727 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4728 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004729 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004730 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004731
4732 mFocusedWindow =
4733 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004734 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004735 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004736
4737 // Set focused application.
4738 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004739 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004740
4741 // Expect one focus window exist in display.
4742 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004743 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004744 mFocusedWindow->consumeFocusEvent(true);
4745 }
4746
4747 virtual void TearDown() override {
4748 InputDispatcherTest::TearDown();
4749
4750 mUnfocusedWindow.clear();
4751 mFocusedWindow.clear();
4752 }
4753
4754protected:
Chris Yea209fde2020-07-22 13:54:51 -07004755 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004756 sp<FakeWindowHandle> mUnfocusedWindow;
4757 sp<FakeWindowHandle> mFocusedWindow;
4758 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4759 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4760 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4761
4762 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4763
4764 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4765
4766private:
4767 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004768 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004769 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4770 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004771 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004772 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4773 location));
4774 }
4775};
4776
4777// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4778// should be ANR'd first.
4779TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004780 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004781 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4782 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004783 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004784 mFocusedWindow->consumeMotionDown();
4785 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4786 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4787 // We consumed all events, so no ANR
4788 ASSERT_TRUE(mDispatcher->waitForIdle());
4789 mFakePolicy->assertNotifyAnrWasNotCalled();
4790
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004791 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004792 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4793 FOCUSED_WINDOW_LOCATION));
4794 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4795 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004796
4797 const std::chrono::duration timeout =
4798 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004799 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004800 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4801 // sequence to make it consistent
4802 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004803 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004804 mFocusedWindow->consumeMotionDown();
4805 // This cancel is generated because the connection was unresponsive
4806 mFocusedWindow->consumeMotionCancel();
4807 mFocusedWindow->assertNoEvents();
4808 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004809 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004810 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004811 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004812}
4813
4814// If we have 2 windows with identical timeouts that are both unresponsive,
4815// it doesn't matter which order they should have ANR.
4816// But we should receive ANR for both.
4817TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4818 // Set the timeout for unfocused window to match the focused window
4819 mUnfocusedWindow->setDispatchingTimeout(10ms);
4820 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4821
4822 tapOnFocusedWindow();
4823 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004824 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4825 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004826
4827 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004828 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4829 mFocusedWindow->getToken() == anrConnectionToken2);
4830 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4831 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004832
4833 ASSERT_TRUE(mDispatcher->waitForIdle());
4834 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004835
4836 mFocusedWindow->consumeMotionDown();
4837 mFocusedWindow->consumeMotionUp();
4838 mUnfocusedWindow->consumeMotionOutside();
4839
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004840 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4841 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004842
4843 // Both applications should be marked as responsive, in any order
4844 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4845 mFocusedWindow->getToken() == responsiveToken2);
4846 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4847 mUnfocusedWindow->getToken() == responsiveToken2);
4848 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004849}
4850
4851// If a window is already not responding, the second tap on the same window should be ignored.
4852// We should also log an error to account for the dropped event (not tested here).
4853// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4854TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4855 tapOnFocusedWindow();
4856 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4857 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4858 // Receive the events, but don't respond
4859 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4860 ASSERT_TRUE(downEventSequenceNum);
4861 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4862 ASSERT_TRUE(upEventSequenceNum);
4863 const std::chrono::duration timeout =
4864 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004865 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004866
4867 // Tap once again
4868 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004869 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004870 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4871 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004872 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004873 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4874 FOCUSED_WINDOW_LOCATION));
4875 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4876 // valid touch target
4877 mUnfocusedWindow->assertNoEvents();
4878
4879 // Consume the first tap
4880 mFocusedWindow->finishEvent(*downEventSequenceNum);
4881 mFocusedWindow->finishEvent(*upEventSequenceNum);
4882 ASSERT_TRUE(mDispatcher->waitForIdle());
4883 // The second tap did not go to the focused window
4884 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004885 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004886 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004887 mFakePolicy->assertNotifyAnrWasNotCalled();
4888}
4889
4890// If you tap outside of all windows, there will not be ANR
4891TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004892 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004893 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4894 LOCATION_OUTSIDE_ALL_WINDOWS));
4895 ASSERT_TRUE(mDispatcher->waitForIdle());
4896 mFakePolicy->assertNotifyAnrWasNotCalled();
4897}
4898
4899// Since the focused window is paused, tapping on it should not produce any events
4900TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4901 mFocusedWindow->setPaused(true);
4902 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4903
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004904 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004905 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4906 FOCUSED_WINDOW_LOCATION));
4907
4908 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4909 ASSERT_TRUE(mDispatcher->waitForIdle());
4910 // Should not ANR because the window is paused, and touches shouldn't go to it
4911 mFakePolicy->assertNotifyAnrWasNotCalled();
4912
4913 mFocusedWindow->assertNoEvents();
4914 mUnfocusedWindow->assertNoEvents();
4915}
4916
4917/**
4918 * If a window is processing a motion event, and then a key event comes in, the key event should
4919 * not to to the focused window until the motion is processed.
4920 * If a different window becomes focused at this time, the key should go to that window instead.
4921 *
4922 * Warning!!!
4923 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4924 * and the injection timeout that we specify when injecting the key.
4925 * We must have the injection timeout (10ms) be smaller than
4926 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4927 *
4928 * If that value changes, this test should also change.
4929 */
4930TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4931 // Set a long ANR timeout to prevent it from triggering
4932 mFocusedWindow->setDispatchingTimeout(2s);
4933 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4934
4935 tapOnUnfocusedWindow();
4936 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4937 ASSERT_TRUE(downSequenceNum);
4938 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4939 ASSERT_TRUE(upSequenceNum);
4940 // Don't finish the events yet, and send a key
4941 // Injection will succeed because we will eventually give up and send the key to the focused
4942 // window even if motions are still being processed.
4943
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004944 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004945 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004946 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4947 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004948 // Key will not be sent to the window, yet, because the window is still processing events
4949 // and the key remains pending, waiting for the touch events to be processed
4950 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4951 ASSERT_FALSE(keySequenceNum);
4952
4953 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004954 mFocusedWindow->setFocusable(false);
4955 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004956 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004957 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004958
4959 // Focus events should precede the key events
4960 mUnfocusedWindow->consumeFocusEvent(true);
4961 mFocusedWindow->consumeFocusEvent(false);
4962
4963 // Finish the tap events, which should unblock dispatcher
4964 mUnfocusedWindow->finishEvent(*downSequenceNum);
4965 mUnfocusedWindow->finishEvent(*upSequenceNum);
4966
4967 // Now that all queues are cleared and no backlog in the connections, the key event
4968 // can finally go to the newly focused "mUnfocusedWindow".
4969 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4970 mFocusedWindow->assertNoEvents();
4971 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004972 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004973}
4974
4975// When the touch stream is split across 2 windows, and one of them does not respond,
4976// then ANR should be raised and the touch should be canceled for the unresponsive window.
4977// The other window should not be affected by that.
4978TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
4979 // Touch Window 1
4980 NotifyMotionArgs motionArgs =
4981 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4982 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
4983 mDispatcher->notifyMotion(&motionArgs);
4984 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4985 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4986
4987 // Touch Window 2
4988 int32_t actionPointerDown =
4989 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4990
4991 motionArgs =
4992 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4993 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
4994 mDispatcher->notifyMotion(&motionArgs);
4995
4996 const std::chrono::duration timeout =
4997 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004998 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004999
5000 mUnfocusedWindow->consumeMotionDown();
5001 mFocusedWindow->consumeMotionDown();
5002 // Focused window may or may not receive ACTION_MOVE
5003 // But it should definitely receive ACTION_CANCEL due to the ANR
5004 InputEvent* event;
5005 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5006 ASSERT_TRUE(moveOrCancelSequenceNum);
5007 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5008 ASSERT_NE(nullptr, event);
5009 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5010 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5011 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5012 mFocusedWindow->consumeMotionCancel();
5013 } else {
5014 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5015 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005016 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005017 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005018
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005019 mUnfocusedWindow->assertNoEvents();
5020 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005021 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005022}
5023
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005024/**
5025 * If we have no focused window, and a key comes in, we start the ANR timer.
5026 * The focused application should add a focused window before the timer runs out to prevent ANR.
5027 *
5028 * If the user touches another application during this time, the key should be dropped.
5029 * Next, if a new focused window comes in, without toggling the focused application,
5030 * then no ANR should occur.
5031 *
5032 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5033 * but in some cases the policy may not update the focused application.
5034 */
5035TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5036 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5037 std::make_shared<FakeApplicationHandle>();
5038 focusedApplication->setDispatchingTimeout(60ms);
5039 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5040 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5041 mFocusedWindow->setFocusable(false);
5042
5043 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5044 mFocusedWindow->consumeFocusEvent(false);
5045
5046 // Send a key. The ANR timer should start because there is no focused window.
5047 // 'focusedApplication' will get blamed if this timer completes.
5048 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005049 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005050 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005051 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5052 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005053 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005054
5055 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5056 // then the injected touches won't cause the focused event to get dropped.
5057 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5058 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5059 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5060 // For this test, it means that the key would get delivered to the window once it becomes
5061 // focused.
5062 std::this_thread::sleep_for(10ms);
5063
5064 // Touch unfocused window. This should force the pending key to get dropped.
5065 NotifyMotionArgs motionArgs =
5066 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5067 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5068 mDispatcher->notifyMotion(&motionArgs);
5069
5070 // We do not consume the motion right away, because that would require dispatcher to first
5071 // process (== drop) the key event, and by that time, ANR will be raised.
5072 // Set the focused window first.
5073 mFocusedWindow->setFocusable(true);
5074 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5075 setFocusedWindow(mFocusedWindow);
5076 mFocusedWindow->consumeFocusEvent(true);
5077 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5078 // to another application. This could be a bug / behaviour in the policy.
5079
5080 mUnfocusedWindow->consumeMotionDown();
5081
5082 ASSERT_TRUE(mDispatcher->waitForIdle());
5083 // Should not ANR because we actually have a focused window. It was just added too slowly.
5084 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5085}
5086
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005087// These tests ensure we cannot send touch events to a window that's positioned behind a window
5088// that has feature NO_INPUT_CHANNEL.
5089// Layout:
5090// Top (closest to user)
5091// mNoInputWindow (above all windows)
5092// mBottomWindow
5093// Bottom (furthest from user)
5094class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5095 virtual void SetUp() override {
5096 InputDispatcherTest::SetUp();
5097
5098 mApplication = std::make_shared<FakeApplicationHandle>();
5099 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5100 "Window without input channel", ADISPLAY_ID_DEFAULT,
5101 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5102
chaviw3277faf2021-05-19 16:45:23 -05005103 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005104 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5105 // It's perfectly valid for this window to not have an associated input channel
5106
5107 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5108 ADISPLAY_ID_DEFAULT);
5109 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5110
5111 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5112 }
5113
5114protected:
5115 std::shared_ptr<FakeApplicationHandle> mApplication;
5116 sp<FakeWindowHandle> mNoInputWindow;
5117 sp<FakeWindowHandle> mBottomWindow;
5118};
5119
5120TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5121 PointF touchedPoint = {10, 10};
5122
5123 NotifyMotionArgs motionArgs =
5124 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5125 ADISPLAY_ID_DEFAULT, {touchedPoint});
5126 mDispatcher->notifyMotion(&motionArgs);
5127
5128 mNoInputWindow->assertNoEvents();
5129 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5130 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5131 // and therefore should prevent mBottomWindow from receiving touches
5132 mBottomWindow->assertNoEvents();
5133}
5134
5135/**
5136 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5137 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5138 */
5139TEST_F(InputDispatcherMultiWindowOcclusionTests,
5140 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5141 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5142 "Window with input channel and NO_INPUT_CHANNEL",
5143 ADISPLAY_ID_DEFAULT);
5144
chaviw3277faf2021-05-19 16:45:23 -05005145 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005146 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5147 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5148
5149 PointF touchedPoint = {10, 10};
5150
5151 NotifyMotionArgs motionArgs =
5152 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5153 ADISPLAY_ID_DEFAULT, {touchedPoint});
5154 mDispatcher->notifyMotion(&motionArgs);
5155
5156 mNoInputWindow->assertNoEvents();
5157 mBottomWindow->assertNoEvents();
5158}
5159
Vishnu Nair958da932020-08-21 17:12:37 -07005160class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5161protected:
5162 std::shared_ptr<FakeApplicationHandle> mApp;
5163 sp<FakeWindowHandle> mWindow;
5164 sp<FakeWindowHandle> mMirror;
5165
5166 virtual void SetUp() override {
5167 InputDispatcherTest::SetUp();
5168 mApp = std::make_shared<FakeApplicationHandle>();
5169 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5170 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5171 mWindow->getToken());
5172 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5173 mWindow->setFocusable(true);
5174 mMirror->setFocusable(true);
5175 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5176 }
5177};
5178
5179TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5180 // Request focus on a mirrored window
5181 setFocusedWindow(mMirror);
5182
5183 // window gets focused
5184 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005185 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5186 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005187 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5188}
5189
5190// A focused & mirrored window remains focused only if the window and its mirror are both
5191// focusable.
5192TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5193 setFocusedWindow(mMirror);
5194
5195 // window gets focused
5196 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005197 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5198 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005199 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005200 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5201 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005202 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5203
5204 mMirror->setFocusable(false);
5205 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5206
5207 // window loses focus since one of the windows associated with the token in not focusable
5208 mWindow->consumeFocusEvent(false);
5209
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005210 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5211 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005212 mWindow->assertNoEvents();
5213}
5214
5215// A focused & mirrored window remains focused until the window and its mirror both become
5216// invisible.
5217TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5218 setFocusedWindow(mMirror);
5219
5220 // window gets focused
5221 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005222 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5223 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005224 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005225 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5226 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005227 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5228
5229 mMirror->setVisible(false);
5230 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5231
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005232 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5233 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005234 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005235 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5236 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005237 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5238
5239 mWindow->setVisible(false);
5240 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5241
5242 // window loses focus only after all windows associated with the token become invisible.
5243 mWindow->consumeFocusEvent(false);
5244
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005245 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5246 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005247 mWindow->assertNoEvents();
5248}
5249
5250// A focused & mirrored window remains focused until both windows are removed.
5251TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5252 setFocusedWindow(mMirror);
5253
5254 // window gets focused
5255 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005256 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5257 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005258 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005259 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5260 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005261 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5262
5263 // single window is removed but the window token remains focused
5264 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5265
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 // Both windows are removed
5274 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5275 mWindow->consumeFocusEvent(false);
5276
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005277 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5278 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005279 mWindow->assertNoEvents();
5280}
5281
5282// Focus request can be pending until one window becomes visible.
5283TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5284 // Request focus on an invisible mirror.
5285 mWindow->setVisible(false);
5286 mMirror->setVisible(false);
5287 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5288 setFocusedWindow(mMirror);
5289
5290 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005291 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005292 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005293 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005294
5295 mMirror->setVisible(true);
5296 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5297
5298 // window gets focused
5299 mWindow->consumeFocusEvent(true);
5300 // window gets the pending key event
5301 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5302}
Prabir Pradhan99987712020-11-10 18:43:05 -08005303
5304class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5305protected:
5306 std::shared_ptr<FakeApplicationHandle> mApp;
5307 sp<FakeWindowHandle> mWindow;
5308 sp<FakeWindowHandle> mSecondWindow;
5309
5310 void SetUp() override {
5311 InputDispatcherTest::SetUp();
5312 mApp = std::make_shared<FakeApplicationHandle>();
5313 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5314 mWindow->setFocusable(true);
5315 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5316 mSecondWindow->setFocusable(true);
5317
5318 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5319 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5320
5321 setFocusedWindow(mWindow);
5322 mWindow->consumeFocusEvent(true);
5323 }
5324
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005325 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5326 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005327 mDispatcher->notifyPointerCaptureChanged(&args);
5328 }
5329
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005330 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5331 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005332 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005333 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5334 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005335 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005336 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005337 }
5338};
5339
5340TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5341 // Ensure that capture cannot be obtained for unfocused windows.
5342 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5343 mFakePolicy->assertSetPointerCaptureNotCalled();
5344 mSecondWindow->assertNoEvents();
5345
5346 // Ensure that capture can be enabled from the focus window.
5347 requestAndVerifyPointerCapture(mWindow, true);
5348
5349 // Ensure that capture cannot be disabled from a window that does not have capture.
5350 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5351 mFakePolicy->assertSetPointerCaptureNotCalled();
5352
5353 // Ensure that capture can be disabled from the window with capture.
5354 requestAndVerifyPointerCapture(mWindow, false);
5355}
5356
5357TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005358 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005359
5360 setFocusedWindow(mSecondWindow);
5361
5362 // Ensure that the capture disabled event was sent first.
5363 mWindow->consumeCaptureEvent(false);
5364 mWindow->consumeFocusEvent(false);
5365 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005366 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005367
5368 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005369 notifyPointerCaptureChanged({});
5370 notifyPointerCaptureChanged(request);
5371 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005372 mWindow->assertNoEvents();
5373 mSecondWindow->assertNoEvents();
5374 mFakePolicy->assertSetPointerCaptureNotCalled();
5375}
5376
5377TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005378 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005379
5380 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005381 notifyPointerCaptureChanged({});
5382 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005383
5384 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005385 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005386 mWindow->consumeCaptureEvent(false);
5387 mWindow->assertNoEvents();
5388}
5389
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005390TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5391 requestAndVerifyPointerCapture(mWindow, true);
5392
5393 // The first window loses focus.
5394 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005395 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005396 mWindow->consumeCaptureEvent(false);
5397
5398 // Request Pointer Capture from the second window before the notification from InputReader
5399 // arrives.
5400 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005401 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005402
5403 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005404 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005405
5406 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005407 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005408
5409 mSecondWindow->consumeFocusEvent(true);
5410 mSecondWindow->consumeCaptureEvent(true);
5411}
5412
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005413TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5414 // App repeatedly enables and disables capture.
5415 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5416 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5417 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5418 mFakePolicy->assertSetPointerCaptureCalled(false);
5419 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5420 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5421
5422 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5423 // first request is now stale, this should do nothing.
5424 notifyPointerCaptureChanged(firstRequest);
5425 mWindow->assertNoEvents();
5426
5427 // InputReader notifies that the second request was enabled.
5428 notifyPointerCaptureChanged(secondRequest);
5429 mWindow->consumeCaptureEvent(true);
5430}
5431
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005432class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5433protected:
5434 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005435
5436 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5437 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5438
5439 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5440 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5441
5442 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5443 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5444 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5445 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5446 MAXIMUM_OBSCURING_OPACITY);
5447
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005448 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005449 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005450 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005451
5452 sp<FakeWindowHandle> mTouchWindow;
5453
5454 virtual void SetUp() override {
5455 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005456 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005457 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5458 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5459 }
5460
5461 virtual void TearDown() override {
5462 InputDispatcherTest::TearDown();
5463 mTouchWindow.clear();
5464 }
5465
chaviw3277faf2021-05-19 16:45:23 -05005466 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5467 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005468 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005469 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005470 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005471 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005472 return window;
5473 }
5474
5475 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5476 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5477 sp<FakeWindowHandle> window =
5478 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5479 // Generate an arbitrary PID based on the UID
5480 window->setOwnerInfo(1777 + (uid % 10000), uid);
5481 return window;
5482 }
5483
5484 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5485 NotifyMotionArgs args =
5486 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5487 ADISPLAY_ID_DEFAULT, points);
5488 mDispatcher->notifyMotion(&args);
5489 }
5490};
5491
5492TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005493 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005494 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005495 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005496
5497 touch();
5498
5499 mTouchWindow->assertNoEvents();
5500}
5501
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005502TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005503 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5504 const sp<FakeWindowHandle>& w =
5505 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5506 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5507
5508 touch();
5509
5510 mTouchWindow->assertNoEvents();
5511}
5512
5513TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005514 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5515 const sp<FakeWindowHandle>& w =
5516 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5517 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5518
5519 touch();
5520
5521 w->assertNoEvents();
5522}
5523
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005524TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005525 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5526 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005527
5528 touch();
5529
5530 mTouchWindow->consumeAnyMotionDown();
5531}
5532
5533TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005534 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005535 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005536 w->setFrame(Rect(0, 0, 50, 50));
5537 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005538
5539 touch({PointF{100, 100}});
5540
5541 mTouchWindow->consumeAnyMotionDown();
5542}
5543
5544TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005545 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005546 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005547 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5548
5549 touch();
5550
5551 mTouchWindow->consumeAnyMotionDown();
5552}
5553
5554TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5555 const sp<FakeWindowHandle>& w =
5556 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5557 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005558
5559 touch();
5560
5561 mTouchWindow->consumeAnyMotionDown();
5562}
5563
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005564TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5565 const sp<FakeWindowHandle>& w =
5566 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5567 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5568
5569 touch();
5570
5571 w->assertNoEvents();
5572}
5573
5574/**
5575 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5576 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5577 * window, the occluding window will still receive ACTION_OUTSIDE event.
5578 */
5579TEST_F(InputDispatcherUntrustedTouchesTest,
5580 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5581 const sp<FakeWindowHandle>& w =
5582 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005583 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005584 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5585
5586 touch();
5587
5588 w->consumeMotionOutside();
5589}
5590
5591TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5592 const sp<FakeWindowHandle>& w =
5593 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005594 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005595 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5596
5597 touch();
5598
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005599 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005600}
5601
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005602TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005603 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005604 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5605 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005606 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5607
5608 touch();
5609
5610 mTouchWindow->consumeAnyMotionDown();
5611}
5612
5613TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5614 const sp<FakeWindowHandle>& w =
5615 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5616 MAXIMUM_OBSCURING_OPACITY);
5617 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005618
5619 touch();
5620
5621 mTouchWindow->consumeAnyMotionDown();
5622}
5623
5624TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005625 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005626 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5627 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005628 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5629
5630 touch();
5631
5632 mTouchWindow->assertNoEvents();
5633}
5634
5635TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5636 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5637 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005638 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5639 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005640 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005641 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5642 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005643 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5644
5645 touch();
5646
5647 mTouchWindow->assertNoEvents();
5648}
5649
5650TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5651 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5652 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005653 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5654 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005655 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005656 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5657 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005658 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5659
5660 touch();
5661
5662 mTouchWindow->consumeAnyMotionDown();
5663}
5664
5665TEST_F(InputDispatcherUntrustedTouchesTest,
5666 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5667 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005668 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5669 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005670 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005671 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5672 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5674
5675 touch();
5676
5677 mTouchWindow->consumeAnyMotionDown();
5678}
5679
5680TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5681 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005682 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5683 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005684 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005685 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5686 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005687 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005688
5689 touch();
5690
5691 mTouchWindow->assertNoEvents();
5692}
5693
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005694TEST_F(InputDispatcherUntrustedTouchesTest,
5695 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5696 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005697 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5698 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005699 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005700 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5701 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005702 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5703
5704 touch();
5705
5706 mTouchWindow->assertNoEvents();
5707}
5708
5709TEST_F(InputDispatcherUntrustedTouchesTest,
5710 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5711 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005712 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5713 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005714 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005715 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5716 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005717 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5718
5719 touch();
5720
5721 mTouchWindow->consumeAnyMotionDown();
5722}
5723
5724TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5725 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005726 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5727 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005728 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5729
5730 touch();
5731
5732 mTouchWindow->consumeAnyMotionDown();
5733}
5734
5735TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5736 const sp<FakeWindowHandle>& w =
5737 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5738 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5739
5740 touch();
5741
5742 mTouchWindow->consumeAnyMotionDown();
5743}
5744
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005745TEST_F(InputDispatcherUntrustedTouchesTest,
5746 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5747 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5748 const sp<FakeWindowHandle>& w =
5749 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5750 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5751
5752 touch();
5753
5754 mTouchWindow->assertNoEvents();
5755}
5756
5757TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5758 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5759 const sp<FakeWindowHandle>& w =
5760 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5761 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5762
5763 touch();
5764
5765 mTouchWindow->consumeAnyMotionDown();
5766}
5767
5768TEST_F(InputDispatcherUntrustedTouchesTest,
5769 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5770 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5771 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005772 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5773 OPACITY_ABOVE_THRESHOLD);
5774 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5775
5776 touch();
5777
5778 mTouchWindow->consumeAnyMotionDown();
5779}
5780
5781TEST_F(InputDispatcherUntrustedTouchesTest,
5782 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5783 const sp<FakeWindowHandle>& w1 =
5784 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5785 OPACITY_BELOW_THRESHOLD);
5786 const sp<FakeWindowHandle>& w2 =
5787 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5788 OPACITY_BELOW_THRESHOLD);
5789 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5790
5791 touch();
5792
5793 mTouchWindow->assertNoEvents();
5794}
5795
5796/**
5797 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5798 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5799 * (which alone would result in allowing touches) does not affect the blocking behavior.
5800 */
5801TEST_F(InputDispatcherUntrustedTouchesTest,
5802 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5803 const sp<FakeWindowHandle>& wB =
5804 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5805 OPACITY_BELOW_THRESHOLD);
5806 const sp<FakeWindowHandle>& wC =
5807 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5808 OPACITY_BELOW_THRESHOLD);
5809 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5810
5811 touch();
5812
5813 mTouchWindow->assertNoEvents();
5814}
5815
5816/**
5817 * This test is testing that a window from a different UID but with same application token doesn't
5818 * block the touch. Apps can share the application token for close UI collaboration for example.
5819 */
5820TEST_F(InputDispatcherUntrustedTouchesTest,
5821 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5822 const sp<FakeWindowHandle>& w =
5823 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5824 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005825 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5826
5827 touch();
5828
5829 mTouchWindow->consumeAnyMotionDown();
5830}
5831
arthurhungb89ccb02020-12-30 16:19:01 +08005832class InputDispatcherDragTests : public InputDispatcherTest {
5833protected:
5834 std::shared_ptr<FakeApplicationHandle> mApp;
5835 sp<FakeWindowHandle> mWindow;
5836 sp<FakeWindowHandle> mSecondWindow;
5837 sp<FakeWindowHandle> mDragWindow;
5838
5839 void SetUp() override {
5840 InputDispatcherTest::SetUp();
5841 mApp = std::make_shared<FakeApplicationHandle>();
5842 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5843 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005844
5845 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5846 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005847
5848 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5849 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5850 }
5851
5852 // Start performing drag, we will create a drag window and transfer touch to it.
5853 void performDrag() {
5854 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5855 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5856 {50, 50}))
5857 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5858
5859 // Window should receive motion event.
5860 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5861
5862 // The drag window covers the entire display
5863 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5864 mDispatcher->setInputWindows(
5865 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5866
5867 // Transfer touch focus to the drag window
5868 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5869 true /* isDragDrop */);
5870 mWindow->consumeMotionCancel();
5871 mDragWindow->consumeMotionDown();
5872 }
arthurhung6d4bed92021-03-17 11:59:33 +08005873
5874 // Start performing drag, we will create a drag window and transfer touch to it.
5875 void performStylusDrag() {
5876 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5877 injectMotionEvent(mDispatcher,
5878 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5879 AINPUT_SOURCE_STYLUS)
5880 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5881 .pointer(PointerBuilder(0,
5882 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5883 .x(50)
5884 .y(50))
5885 .build()));
5886 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5887
5888 // The drag window covers the entire display
5889 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5890 mDispatcher->setInputWindows(
5891 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5892
5893 // Transfer touch focus to the drag window
5894 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5895 true /* isDragDrop */);
5896 mWindow->consumeMotionCancel();
5897 mDragWindow->consumeMotionDown();
5898 }
arthurhungb89ccb02020-12-30 16:19:01 +08005899};
5900
5901TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5902 performDrag();
5903
5904 // Move on window.
5905 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5906 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5907 ADISPLAY_ID_DEFAULT, {50, 50}))
5908 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5909 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5910 mWindow->consumeDragEvent(false, 50, 50);
5911 mSecondWindow->assertNoEvents();
5912
5913 // Move to another window.
5914 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5915 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5916 ADISPLAY_ID_DEFAULT, {150, 50}))
5917 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5918 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5919 mWindow->consumeDragEvent(true, 150, 50);
5920 mSecondWindow->consumeDragEvent(false, 50, 50);
5921
5922 // Move back to original window.
5923 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5924 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5925 ADISPLAY_ID_DEFAULT, {50, 50}))
5926 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5927 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5928 mWindow->consumeDragEvent(false, 50, 50);
5929 mSecondWindow->consumeDragEvent(true, -50, 50);
5930
5931 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5932 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5933 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5934 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5935 mWindow->assertNoEvents();
5936 mSecondWindow->assertNoEvents();
5937}
5938
arthurhungf452d0b2021-01-06 00:19:52 +08005939TEST_F(InputDispatcherDragTests, DragAndDrop) {
5940 performDrag();
5941
5942 // Move on window.
5943 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5944 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5945 ADISPLAY_ID_DEFAULT, {50, 50}))
5946 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5947 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5948 mWindow->consumeDragEvent(false, 50, 50);
5949 mSecondWindow->assertNoEvents();
5950
5951 // Move to another window.
5952 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5953 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5954 ADISPLAY_ID_DEFAULT, {150, 50}))
5955 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5956 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5957 mWindow->consumeDragEvent(true, 150, 50);
5958 mSecondWindow->consumeDragEvent(false, 50, 50);
5959
5960 // drop to another window.
5961 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5962 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5963 {150, 50}))
5964 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5965 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5966 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5967 mWindow->assertNoEvents();
5968 mSecondWindow->assertNoEvents();
5969}
5970
arthurhung6d4bed92021-03-17 11:59:33 +08005971TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
5972 performStylusDrag();
5973
5974 // Move on window and keep button pressed.
5975 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5976 injectMotionEvent(mDispatcher,
5977 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5978 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5979 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5980 .x(50)
5981 .y(50))
5982 .build()))
5983 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5984 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5985 mWindow->consumeDragEvent(false, 50, 50);
5986 mSecondWindow->assertNoEvents();
5987
5988 // Move to another window and release button, expect to drop item.
5989 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5990 injectMotionEvent(mDispatcher,
5991 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
5992 .buttonState(0)
5993 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
5994 .x(150)
5995 .y(50))
5996 .build()))
5997 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5998 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5999 mWindow->assertNoEvents();
6000 mSecondWindow->assertNoEvents();
6001 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6002
6003 // nothing to the window.
6004 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6005 injectMotionEvent(mDispatcher,
6006 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6007 .buttonState(0)
6008 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6009 .x(150)
6010 .y(50))
6011 .build()))
6012 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6013 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6014 mWindow->assertNoEvents();
6015 mSecondWindow->assertNoEvents();
6016}
6017
Arthur Hung6d0571e2021-04-09 20:18:16 +08006018TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6019 performDrag();
6020
6021 // Set second window invisible.
6022 mSecondWindow->setVisible(false);
6023 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6024
6025 // Move on window.
6026 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6027 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6028 ADISPLAY_ID_DEFAULT, {50, 50}))
6029 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6030 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6031 mWindow->consumeDragEvent(false, 50, 50);
6032 mSecondWindow->assertNoEvents();
6033
6034 // Move to another window.
6035 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6036 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6037 ADISPLAY_ID_DEFAULT, {150, 50}))
6038 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6039 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6040 mWindow->consumeDragEvent(true, 150, 50);
6041 mSecondWindow->assertNoEvents();
6042
6043 // drop to another window.
6044 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6045 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6046 {150, 50}))
6047 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6048 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6049 mFakePolicy->assertDropTargetEquals(nullptr);
6050 mWindow->assertNoEvents();
6051 mSecondWindow->assertNoEvents();
6052}
6053
Vishnu Nair062a8672021-09-03 16:07:44 -07006054class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6055
6056TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6057 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6058 sp<FakeWindowHandle> window =
6059 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6060 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
6061 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6062 window->setFocusable(true);
6063 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6064 setFocusedWindow(window);
6065 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6066
6067 // With the flag set, window should not get any input
6068 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6069 mDispatcher->notifyKey(&keyArgs);
6070 window->assertNoEvents();
6071
6072 NotifyMotionArgs motionArgs =
6073 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6074 ADISPLAY_ID_DEFAULT);
6075 mDispatcher->notifyMotion(&motionArgs);
6076 window->assertNoEvents();
6077
6078 // With the flag cleared, the window should get input
6079 window->setInputFeatures({});
6080 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6081
6082 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6083 mDispatcher->notifyKey(&keyArgs);
6084 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6085
6086 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6087 ADISPLAY_ID_DEFAULT);
6088 mDispatcher->notifyMotion(&motionArgs);
6089 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6090 window->assertNoEvents();
6091}
6092
6093TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6094 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6095 std::make_shared<FakeApplicationHandle>();
6096 sp<FakeWindowHandle> obscuringWindow =
6097 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6098 ADISPLAY_ID_DEFAULT);
6099 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6100 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006101 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006102 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6103 sp<FakeWindowHandle> window =
6104 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6105 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6106 window->setOwnerInfo(222, 222);
6107 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6108 window->setFocusable(true);
6109 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6110 setFocusedWindow(window);
6111 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6112
6113 // With the flag set, window should not get any input
6114 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6115 mDispatcher->notifyKey(&keyArgs);
6116 window->assertNoEvents();
6117
6118 NotifyMotionArgs motionArgs =
6119 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6120 ADISPLAY_ID_DEFAULT);
6121 mDispatcher->notifyMotion(&motionArgs);
6122 window->assertNoEvents();
6123
6124 // With the flag cleared, the window should get input
6125 window->setInputFeatures({});
6126 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6127
6128 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6129 mDispatcher->notifyKey(&keyArgs);
6130 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6131
6132 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6133 ADISPLAY_ID_DEFAULT);
6134 mDispatcher->notifyMotion(&motionArgs);
6135 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6136 window->assertNoEvents();
6137}
6138
6139TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6140 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6141 std::make_shared<FakeApplicationHandle>();
6142 sp<FakeWindowHandle> obscuringWindow =
6143 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6144 ADISPLAY_ID_DEFAULT);
6145 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6146 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006147 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006148 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6149 sp<FakeWindowHandle> window =
6150 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6151 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6152 window->setOwnerInfo(222, 222);
6153 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6154 window->setFocusable(true);
6155 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6156 setFocusedWindow(window);
6157 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6158
6159 // With the flag set, window should not get any input
6160 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6161 mDispatcher->notifyKey(&keyArgs);
6162 window->assertNoEvents();
6163
6164 NotifyMotionArgs motionArgs =
6165 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6166 ADISPLAY_ID_DEFAULT);
6167 mDispatcher->notifyMotion(&motionArgs);
6168 window->assertNoEvents();
6169
6170 // When the window is no longer obscured because it went on top, it should get input
6171 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6172
6173 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6174 mDispatcher->notifyKey(&keyArgs);
6175 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6176
6177 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6178 ADISPLAY_ID_DEFAULT);
6179 mDispatcher->notifyMotion(&motionArgs);
6180 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6181 window->assertNoEvents();
6182}
6183
Antonio Kantekf16f2832021-09-28 04:39:20 +00006184class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6185protected:
6186 std::shared_ptr<FakeApplicationHandle> mApp;
6187 sp<FakeWindowHandle> mWindow;
6188 sp<FakeWindowHandle> mSecondWindow;
6189
6190 void SetUp() override {
6191 InputDispatcherTest::SetUp();
6192
6193 mApp = std::make_shared<FakeApplicationHandle>();
6194 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6195 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006196 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006197 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6198 mSecondWindow->setFocusable(true);
6199
6200 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6201 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006202 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006203
6204 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
6205 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, INJECTOR_PID,
6206 INJECTOR_UID, /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006207 }
6208
Antonio Kantekea47acb2021-12-23 12:41:25 -08006209 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006210 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006211 mWindow->consumeTouchModeEvent(inTouchMode);
6212 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6213 }
6214};
6215
Antonio Kantek26defcf2022-02-08 01:12:27 +00006216TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006217 const WindowInfo& windowInfo = *mWindow->getInfo();
6218 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6219 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006220}
6221
Antonio Kantek26defcf2022-02-08 01:12:27 +00006222TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6223 const WindowInfo& windowInfo = *mWindow->getInfo();
6224 int32_t ownerPid = windowInfo.ownerPid;
6225 int32_t ownerUid = windowInfo.ownerUid;
6226 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6227 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6228 ownerUid, /* hasPermission */ false));
6229 mWindow->assertNoEvents();
6230 mSecondWindow->assertNoEvents();
6231}
6232
6233TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6234 const WindowInfo& windowInfo = *mWindow->getInfo();
6235 int32_t ownerPid = windowInfo.ownerPid;
6236 int32_t ownerUid = windowInfo.ownerUid;
6237 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6238 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6239 /* hasPermission */ true);
6240}
6241
Antonio Kantekf16f2832021-09-28 04:39:20 +00006242TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006243 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006244 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6245 windowInfo.ownerPid, windowInfo.ownerUid,
6246 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006247 mWindow->assertNoEvents();
6248 mSecondWindow->assertNoEvents();
6249}
6250
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006251class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6252public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006253 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006254 std::shared_ptr<FakeApplicationHandle> application =
6255 std::make_shared<FakeApplicationHandle>();
6256 std::string name = "Fake Spy ";
6257 name += std::to_string(mSpyCount++);
6258 sp<FakeWindowHandle> spy =
6259 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
6260 spy->setInputFeatures(WindowInfo::Feature::SPY);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006261 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006262 return spy;
6263 }
6264
6265 sp<FakeWindowHandle> createForeground() {
6266 std::shared_ptr<FakeApplicationHandle> application =
6267 std::make_shared<FakeApplicationHandle>();
6268 sp<FakeWindowHandle> window =
6269 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006270 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006271 return window;
6272 }
6273
6274private:
6275 int mSpyCount{0};
6276};
6277
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006278using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006279/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006280 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6281 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006282TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6283 ScopedSilentDeath _silentDeath;
6284
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006285 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006286 spy->setTrustedOverlay(false);
6287 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6288 ".* not a trusted overlay");
6289}
6290
6291/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006292 * Input injection into a display with a spy window but no foreground windows should succeed.
6293 */
6294TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006295 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006296 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6297
6298 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6299 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6300 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6301 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6302}
6303
6304/**
6305 * Verify the order in which different input windows receive events. The touched foreground window
6306 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6307 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6308 * receive events before ones belows it.
6309 *
6310 * Here, we set up a scenario with four windows in the following Z order from the top:
6311 * spy1, spy2, window, spy3.
6312 * We then inject an event and verify that the foreground "window" receives it first, followed by
6313 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6314 * window.
6315 */
6316TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6317 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006318 auto spy1 = createSpy();
6319 auto spy2 = createSpy();
6320 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006321 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6322 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6323 const size_t numChannels = channels.size();
6324
Michael Wright8e9a8562022-02-09 13:44:29 +00006325 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006326 if (!epollFd.ok()) {
6327 FAIL() << "Failed to create epoll fd";
6328 }
6329
6330 for (size_t i = 0; i < numChannels; i++) {
6331 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6332 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6333 FAIL() << "Failed to add fd to epoll";
6334 }
6335 }
6336
6337 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6338 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6339 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6340
6341 std::vector<size_t> eventOrder;
6342 std::vector<struct epoll_event> events(numChannels);
6343 for (;;) {
6344 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6345 (100ms).count());
6346 if (nFds < 0) {
6347 FAIL() << "Failed to call epoll_wait";
6348 }
6349 if (nFds == 0) {
6350 break; // epoll_wait timed out
6351 }
6352 for (int i = 0; i < nFds; i++) {
6353 ASSERT_EQ(EPOLLIN, events[i].events);
6354 eventOrder.push_back(events[i].data.u64);
6355 channels[i]->consumeMotionDown();
6356 }
6357 }
6358
6359 // Verify the order in which the events were received.
6360 EXPECT_EQ(3u, eventOrder.size());
6361 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6362 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6363 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6364}
6365
6366/**
6367 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6368 */
6369TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6370 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006371 auto spy = createSpy();
6372 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006373 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6374
6375 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6376 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6377 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6378 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6379 spy->assertNoEvents();
6380}
6381
6382/**
6383 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6384 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6385 * to the window.
6386 */
6387TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6388 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006389 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006390 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6391 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6392
6393 // Inject an event outside the spy window's touchable region.
6394 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6395 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6396 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6397 window->consumeMotionDown();
6398 spy->assertNoEvents();
6399 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6400 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6401 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6402 window->consumeMotionUp();
6403 spy->assertNoEvents();
6404
6405 // Inject an event inside the spy window's touchable region.
6406 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6407 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6408 {5, 10}))
6409 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6410 window->consumeMotionDown();
6411 spy->consumeMotionDown();
6412}
6413
6414/**
6415 * A spy window that is a modal window will receive gestures outside of its frame and touchable
6416 * region.
6417 */
6418TEST_F(InputDispatcherSpyWindowTest, ModalWindow) {
6419 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006420 auto spy = createSpy();
6421 // Our current policy dictates that modal windows must be focusable.
6422 spy->setFocusable(true);
6423 spy->setTouchModal(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006424 spy->setFrame(Rect{0, 0, 20, 20});
6425 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6426
6427 // Inject an event outside the spy window's frame and touchable region.
6428 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6429 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6430 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6431 window->consumeMotionDown();
6432 spy->consumeMotionDown();
6433}
6434
6435/**
6436 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006437 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006438 */
6439TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6440 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006441 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006442 auto spy = createSpy();
6443 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006444 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006445 spy->setFrame(Rect{0, 0, 20, 20});
6446 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6447
6448 // Inject an event outside the spy window's frame and touchable region.
6449 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006450 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6451 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006452 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6453 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006454 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006455}
6456
6457/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006458 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6459 * any other windows - including other spy windows - will also be cancelled.
6460 */
6461TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6462 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006463 auto spy1 = createSpy();
6464 auto spy2 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006465 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6466
6467 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6468 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6469 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6470 window->consumeMotionDown();
6471 spy1->consumeMotionDown();
6472 spy2->consumeMotionDown();
6473
6474 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006475 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006476 spy2->assertNoEvents();
6477 spy1->consumeMotionCancel();
6478 window->consumeMotionCancel();
6479
6480 // The rest of the gesture should only be sent to the second spy window.
6481 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6482 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6483 ADISPLAY_ID_DEFAULT))
6484 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6485 spy2->consumeMotionMove();
6486 spy1->assertNoEvents();
6487 window->assertNoEvents();
6488}
6489
6490/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006491 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
6492 * in the middle of the gesture.
6493 */
6494TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
6495 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006496 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006497 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6498
6499 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6500 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6501 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6502 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6503 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6504
6505 window->releaseChannel();
6506
6507 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6508
6509 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6510 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6511 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6512 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6513}
6514
6515/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006516 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
6517 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006518 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006519TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006520 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006521 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006522
6523 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6524
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006525 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006526 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6527 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6528 {100, 200}))
6529 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006530 spy->consumeMotionDown();
6531 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006532
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006533 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006534 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006535 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006536
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006537 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006538 const MotionEvent secondFingerDownEvent =
6539 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6540 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6541 AINPUT_SOURCE_TOUCHSCREEN)
6542 .displayId(ADISPLAY_ID_DEFAULT)
6543 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6544 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6545 .x(100)
6546 .y(200))
6547 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6548 .build();
6549 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6550 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6551 InputEventInjectionSync::WAIT_FOR_RESULT))
6552 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6553
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006554 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6555
6556 // Third finger goes down outside all windows, so injection should fail.
6557 const MotionEvent thirdFingerDownEvent =
6558 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6559 (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6560 AINPUT_SOURCE_TOUCHSCREEN)
6561 .displayId(ADISPLAY_ID_DEFAULT)
6562 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6563 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6564 .x(100)
6565 .y(200))
6566 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6567 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
6568 .build();
6569 ASSERT_EQ(InputEventInjectionResult::FAILED,
6570 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
6571 InputEventInjectionSync::WAIT_FOR_RESULT))
6572 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6573
6574 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006575 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006576}
6577
6578/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006579 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6580 * pointers that are down within its bounds.
6581 */
6582TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6583 auto windowLeft = createForeground();
6584 windowLeft->setFrame({0, 0, 100, 200});
6585 auto windowRight = createForeground();
6586 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006587 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006588 spy->setFrame({0, 0, 200, 200});
6589 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6590
6591 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6592 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6593 {50, 50}))
6594 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6595 windowLeft->consumeMotionDown();
6596 spy->consumeMotionDown();
6597
6598 const MotionEvent secondFingerDownEvent =
6599 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6600 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6601 AINPUT_SOURCE_TOUCHSCREEN)
6602 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6603 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6604 .pointer(
6605 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6606 .build();
6607 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6608 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6609 InputEventInjectionSync::WAIT_FOR_RESULT))
6610 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6611 windowRight->consumeMotionDown();
6612 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6613}
6614
6615/**
6616 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6617 * the spy should receive the second pointer with ACTION_DOWN.
6618 */
6619TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6620 auto window = createForeground();
6621 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006622 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006623 spyRight->setFrame({100, 0, 200, 200});
6624 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6625
6626 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6627 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6628 {50, 50}))
6629 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6630 window->consumeMotionDown();
6631 spyRight->assertNoEvents();
6632
6633 const MotionEvent secondFingerDownEvent =
6634 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6635 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6636 AINPUT_SOURCE_TOUCHSCREEN)
6637 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6638 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6639 .pointer(
6640 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6641 .build();
6642 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6643 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6644 InputEventInjectionSync::WAIT_FOR_RESULT))
6645 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6646 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6647 spyRight->consumeMotionDown();
6648}
6649
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006650/**
6651 * The spy window should not be able to affect whether or not touches are split. Only the foreground
6652 * windows should be allowed to control split touch.
6653 */
6654TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006655 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006656 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006657 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006658 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006659
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006660 auto window = createForeground();
6661 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006662
6663 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6664
6665 // First finger down, no window touched.
6666 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6667 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6668 {100, 200}))
6669 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6670 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6671 window->assertNoEvents();
6672
6673 // Second finger down on window, the window should receive touch down.
6674 const MotionEvent secondFingerDownEvent =
6675 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6676 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6677 AINPUT_SOURCE_TOUCHSCREEN)
6678 .displayId(ADISPLAY_ID_DEFAULT)
6679 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6680 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6681 .x(100)
6682 .y(200))
6683 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6684 .build();
6685 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6686 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6687 InputEventInjectionSync::WAIT_FOR_RESULT))
6688 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6689
6690 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6691 spy->consumeMotionPointerDown(1 /* pointerIndex */);
6692}
6693
6694/**
6695 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
6696 * do not receive key events.
6697 */
6698TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006699 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006700 spy->setFocusable(false);
6701
6702 auto window = createForeground();
6703 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6704 setFocusedWindow(window);
6705 window->consumeFocusEvent(true);
6706
6707 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6708 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6709 window->consumeKeyDown(ADISPLAY_ID_NONE);
6710
6711 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6712 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6713 window->consumeKeyUp(ADISPLAY_ID_NONE);
6714
6715 spy->assertNoEvents();
6716}
6717
Prabir Pradhand65552b2021-10-07 11:23:50 -07006718class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6719public:
6720 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6721 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6722 std::make_shared<FakeApplicationHandle>();
6723 sp<FakeWindowHandle> overlay =
6724 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6725 ADISPLAY_ID_DEFAULT);
6726 overlay->setFocusable(false);
6727 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006728 overlay->setTouchable(false);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006729 overlay->setInputFeatures(WindowInfo::Feature::INTERCEPTS_STYLUS);
6730 overlay->setTrustedOverlay(true);
6731
6732 std::shared_ptr<FakeApplicationHandle> application =
6733 std::make_shared<FakeApplicationHandle>();
6734 sp<FakeWindowHandle> window =
6735 new FakeWindowHandle(application, mDispatcher, "Application window",
6736 ADISPLAY_ID_DEFAULT);
6737 window->setFocusable(true);
6738 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006739
6740 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6741 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6742 setFocusedWindow(window);
6743 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6744 return {std::move(overlay), std::move(window)};
6745 }
6746
6747 void sendFingerEvent(int32_t action) {
6748 NotifyMotionArgs motionArgs =
6749 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6750 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6751 mDispatcher->notifyMotion(&motionArgs);
6752 }
6753
6754 void sendStylusEvent(int32_t action) {
6755 NotifyMotionArgs motionArgs =
6756 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6757 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6758 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6759 mDispatcher->notifyMotion(&motionArgs);
6760 }
6761};
6762
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006763using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
6764
6765TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
6766 ScopedSilentDeath _silentDeath;
6767
Prabir Pradhand65552b2021-10-07 11:23:50 -07006768 auto [overlay, window] = setupStylusOverlayScenario();
6769 overlay->setTrustedOverlay(false);
6770 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6771 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6772 ".* not a trusted overlay");
6773}
6774
6775TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6776 auto [overlay, window] = setupStylusOverlayScenario();
6777 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6778
6779 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6780 overlay->consumeMotionDown();
6781 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6782 overlay->consumeMotionUp();
6783
6784 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6785 window->consumeMotionDown();
6786 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6787 window->consumeMotionUp();
6788
6789 overlay->assertNoEvents();
6790 window->assertNoEvents();
6791}
6792
6793TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6794 auto [overlay, window] = setupStylusOverlayScenario();
6795 overlay->setInputFeatures(overlay->getInfo()->inputFeatures | WindowInfo::Feature::SPY);
6796 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6797
6798 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6799 overlay->consumeMotionDown();
6800 window->consumeMotionDown();
6801 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6802 overlay->consumeMotionUp();
6803 window->consumeMotionUp();
6804
6805 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6806 window->consumeMotionDown();
6807 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6808 window->consumeMotionUp();
6809
6810 overlay->assertNoEvents();
6811 window->assertNoEvents();
6812}
6813
Garfield Tane84e6f92019-08-29 17:28:41 -07006814} // namespace android::inputdispatcher