blob: 1950a7f463fe2bdd157c9fbdc378bb9e0eb191ac [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;
chaviw3277faf2021-05-19 16:45:23 -0500990 mInfo.type = WindowInfo::Type::APPLICATION;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -0500991 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000992 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -0800993 mInfo.frameLeft = 0;
994 mInfo.frameTop = 0;
995 mInfo.frameRight = WIDTH;
996 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -0700997 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -0800998 mInfo.globalScaleFactor = 1.0;
999 mInfo.touchableRegion.clear();
1000 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
1001 mInfo.visible = true;
Vishnu Nair47074b82020-08-14 11:54:47 -07001002 mInfo.focusable = false;
chaviwd1c23182019-12-20 18:44:56 -08001003 mInfo.hasWallpaper = false;
1004 mInfo.paused = false;
chaviwd1c23182019-12-20 18:44:56 -08001005 mInfo.ownerPid = INJECTOR_PID;
1006 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -08001007 mInfo.displayId = displayId;
Prabir Pradhand65552b2021-10-07 11:23:50 -07001008 mInfo.trustedOverlay = false;
chaviwd1c23182019-12-20 18:44:56 -08001009 }
1010
Arthur Hungabbb9d82021-09-01 14:52:30 +00001011 sp<FakeWindowHandle> clone(
1012 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001013 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001014 sp<FakeWindowHandle> handle =
1015 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1016 displayId, mInfo.token);
1017 return handle;
1018 }
1019
Vishnu Nair47074b82020-08-14 11:54:47 -07001020 void setFocusable(bool focusable) { mInfo.focusable = focusable; }
chaviwd1c23182019-12-20 18:44:56 -08001021
Vishnu Nair958da932020-08-21 17:12:37 -07001022 void setVisible(bool visible) { mInfo.visible = visible; }
1023
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001024 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001025 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001026 }
1027
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001028 void setPaused(bool paused) { mInfo.paused = paused; }
1029
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001030 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1031
chaviw3277faf2021-05-19 16:45:23 -05001032 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001033
Bernardo Rufino7393d172021-02-26 13:56:11 +00001034 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1035
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001036 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001037 mInfo.frameLeft = frame.left;
1038 mInfo.frameTop = frame.top;
1039 mInfo.frameRight = frame.right;
1040 mInfo.frameBottom = frame.bottom;
1041 mInfo.touchableRegion.clear();
1042 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001043
1044 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1045 ui::Transform translate;
1046 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1047 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001048 }
1049
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001050 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1051
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001052 void setType(WindowInfo::Type type) { mInfo.type = type; }
1053
1054 void setHasWallpaper(bool hasWallpaper) { mInfo.hasWallpaper = hasWallpaper; }
1055
chaviw3277faf2021-05-19 16:45:23 -05001056 void addFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags |= flags; }
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00001057
chaviw3277faf2021-05-19 16:45:23 -05001058 void setFlags(Flags<WindowInfo::Flag> flags) { mInfo.flags = flags; }
chaviwd1c23182019-12-20 18:44:56 -08001059
Prabir Pradhand65552b2021-10-07 11:23:50 -07001060 void setInputFeatures(Flags<WindowInfo::Feature> features) { mInfo.inputFeatures = features; }
1061
1062 void setTrustedOverlay(bool trustedOverlay) { mInfo.trustedOverlay = trustedOverlay; }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001063
chaviw9eaa22c2020-07-01 16:21:27 -07001064 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1065 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1066 }
1067
1068 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001069
yunho.shinf4a80b82020-11-16 21:13:57 +09001070 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1071
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001072 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1073 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1074 expectedFlags);
1075 }
1076
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001077 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1078 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1079 }
1080
Svet Ganov5d3bc372020-01-26 23:11:07 -08001081 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001082 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001083 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1084 expectedFlags);
1085 }
1086
1087 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001088 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001089 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1090 expectedFlags);
1091 }
1092
1093 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001094 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001095 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1096 }
1097
1098 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1099 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001100 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1101 expectedFlags);
1102 }
1103
Svet Ganov5d3bc372020-01-26 23:11:07 -08001104 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001105 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1106 int32_t expectedFlags = 0) {
1107 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1108 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001109 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1110 }
1111
1112 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001113 int32_t expectedFlags = 0) {
1114 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1115 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001116 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1117 }
1118
1119 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001120 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001121 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1122 expectedFlags);
1123 }
1124
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001125 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1126 int32_t expectedFlags = 0) {
1127 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1128 expectedFlags);
1129 }
1130
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001131 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1132 int32_t expectedFlags = 0) {
1133 InputEvent* event = consume();
1134 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1135 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1136 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1137 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1138 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1139 }
1140
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001141 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1142 ASSERT_NE(mInputReceiver, nullptr)
1143 << "Cannot consume events from a window with no receiver";
1144 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1145 }
1146
Prabir Pradhan99987712020-11-10 18:43:05 -08001147 void consumeCaptureEvent(bool hasCapture) {
1148 ASSERT_NE(mInputReceiver, nullptr)
1149 << "Cannot consume events from a window with no receiver";
1150 mInputReceiver->consumeCaptureEvent(hasCapture);
1151 }
1152
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001153 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1154 std::optional<int32_t> expectedDisplayId,
1155 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001156 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1157 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1158 expectedFlags);
1159 }
1160
arthurhungb89ccb02020-12-30 16:19:01 +08001161 void consumeDragEvent(bool isExiting, float x, float y) {
1162 mInputReceiver->consumeDragEvent(isExiting, x, y);
1163 }
1164
Antonio Kantekf16f2832021-09-28 04:39:20 +00001165 void consumeTouchModeEvent(bool inTouchMode) {
1166 ASSERT_NE(mInputReceiver, nullptr)
1167 << "Cannot consume events from a window with no receiver";
1168 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1169 }
1170
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001171 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001172 if (mInputReceiver == nullptr) {
1173 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1174 return std::nullopt;
1175 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001176 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001177 }
1178
1179 void finishEvent(uint32_t sequenceNum) {
1180 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1181 mInputReceiver->finishEvent(sequenceNum);
1182 }
1183
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001184 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1185 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1186 mInputReceiver->sendTimeline(inputEventId, timeline);
1187 }
1188
chaviwaf87b3e2019-10-01 16:59:28 -07001189 InputEvent* consume() {
1190 if (mInputReceiver == nullptr) {
1191 return nullptr;
1192 }
1193 return mInputReceiver->consume();
1194 }
1195
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001196 MotionEvent* consumeMotion() {
1197 InputEvent* event = consume();
1198 if (event == nullptr) {
1199 ADD_FAILURE() << "Consume failed : no event";
1200 return nullptr;
1201 }
1202 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1203 ADD_FAILURE() << "Instead of motion event, got "
1204 << inputEventTypeToString(event->getType());
1205 return nullptr;
1206 }
1207 return static_cast<MotionEvent*>(event);
1208 }
1209
Arthur Hungb92218b2018-08-14 12:00:21 +08001210 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001211 if (mInputReceiver == nullptr &&
chaviw3277faf2021-05-19 16:45:23 -05001212 mInfo.inputFeatures.test(WindowInfo::Feature::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001213 return; // Can't receive events if the window does not have input channel
1214 }
1215 ASSERT_NE(nullptr, mInputReceiver)
1216 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001217 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001218 }
1219
chaviwaf87b3e2019-10-01 16:59:28 -07001220 sp<IBinder> getToken() { return mInfo.token; }
1221
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001222 const std::string& getName() { return mName; }
1223
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001224 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1225 mInfo.ownerPid = ownerPid;
1226 mInfo.ownerUid = ownerUid;
1227 }
1228
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001229 void destroyReceiver() { mInputReceiver = nullptr; }
1230
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001231 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1232
chaviwd1c23182019-12-20 18:44:56 -08001233private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001234 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001235 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001236 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001237};
1238
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001239std::atomic<int32_t> FakeWindowHandle::sId{1};
1240
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001241static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001242 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001243 int32_t displayId = ADISPLAY_ID_NONE,
1244 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001245 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
1246 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001247 KeyEvent event;
1248 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1249
1250 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001251 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001252 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1253 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001254
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001255 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
1256 if (!allowKeyRepeat) {
1257 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1258 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001259 // Inject event until dispatch out.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001260 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001261 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001262}
1263
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001264static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001265 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001266 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1267}
1268
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001269// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1270// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1271// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001272static InputEventInjectionResult injectKeyDownNoRepeat(
1273 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001274 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1275 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1276 /* allowKeyRepeat */ false);
1277}
1278
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001279static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001280 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001281 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1282}
1283
Garfield Tandf26e862020-07-01 20:18:19 -07001284class PointerBuilder {
1285public:
1286 PointerBuilder(int32_t id, int32_t toolType) {
1287 mProperties.clear();
1288 mProperties.id = id;
1289 mProperties.toolType = toolType;
1290 mCoords.clear();
1291 }
1292
1293 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1294
1295 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1296
1297 PointerBuilder& axis(int32_t axis, float value) {
1298 mCoords.setAxisValue(axis, value);
1299 return *this;
1300 }
1301
1302 PointerProperties buildProperties() const { return mProperties; }
1303
1304 PointerCoords buildCoords() const { return mCoords; }
1305
1306private:
1307 PointerProperties mProperties;
1308 PointerCoords mCoords;
1309};
1310
1311class MotionEventBuilder {
1312public:
1313 MotionEventBuilder(int32_t action, int32_t source) {
1314 mAction = action;
1315 mSource = source;
1316 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1317 }
1318
1319 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1320 mEventTime = eventTime;
1321 return *this;
1322 }
1323
1324 MotionEventBuilder& displayId(int32_t displayId) {
1325 mDisplayId = displayId;
1326 return *this;
1327 }
1328
1329 MotionEventBuilder& actionButton(int32_t actionButton) {
1330 mActionButton = actionButton;
1331 return *this;
1332 }
1333
arthurhung6d4bed92021-03-17 11:59:33 +08001334 MotionEventBuilder& buttonState(int32_t buttonState) {
1335 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001336 return *this;
1337 }
1338
1339 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1340 mRawXCursorPosition = rawXCursorPosition;
1341 return *this;
1342 }
1343
1344 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1345 mRawYCursorPosition = rawYCursorPosition;
1346 return *this;
1347 }
1348
1349 MotionEventBuilder& pointer(PointerBuilder pointer) {
1350 mPointers.push_back(pointer);
1351 return *this;
1352 }
1353
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001354 MotionEventBuilder& addFlag(uint32_t flags) {
1355 mFlags |= flags;
1356 return *this;
1357 }
1358
Garfield Tandf26e862020-07-01 20:18:19 -07001359 MotionEvent build() {
1360 std::vector<PointerProperties> pointerProperties;
1361 std::vector<PointerCoords> pointerCoords;
1362 for (const PointerBuilder& pointer : mPointers) {
1363 pointerProperties.push_back(pointer.buildProperties());
1364 pointerCoords.push_back(pointer.buildCoords());
1365 }
1366
1367 // Set mouse cursor position for the most common cases to avoid boilerplate.
1368 if (mSource == AINPUT_SOURCE_MOUSE &&
1369 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1370 mPointers.size() == 1) {
1371 mRawXCursorPosition = pointerCoords[0].getX();
1372 mRawYCursorPosition = pointerCoords[0].getY();
1373 }
1374
1375 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001376 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001377 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001378 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001379 mButtonState, MotionClassification::NONE, identityTransform,
1380 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001381 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1382 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001383
1384 return event;
1385 }
1386
1387private:
1388 int32_t mAction;
1389 int32_t mSource;
1390 nsecs_t mEventTime;
1391 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1392 int32_t mActionButton{0};
1393 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001394 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001395 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1396 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1397
1398 std::vector<PointerBuilder> mPointers;
1399};
1400
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001401static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001402 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001403 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001404 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
Garfield Tandf26e862020-07-01 20:18:19 -07001405 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1406 injectionTimeout,
1407 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
1408}
1409
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001410static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001411 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001412 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001413 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001414 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1415 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001416 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001417 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001418 MotionEvent event = MotionEventBuilder(action, source)
1419 .displayId(displayId)
1420 .eventTime(eventTime)
1421 .rawXCursorPosition(cursorPosition.x)
1422 .rawYCursorPosition(cursorPosition.y)
1423 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1424 .x(position.x)
1425 .y(position.y))
1426 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001427
1428 // Inject event until dispatch out.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001429 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001430}
1431
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001432static InputEventInjectionResult injectMotionDown(
1433 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1434 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001435 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001436}
1437
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001438static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001439 int32_t source, int32_t displayId,
1440 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001441 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001442}
1443
Jackal Guof9696682018-10-05 12:23:23 +08001444static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1445 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1446 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001447 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1448 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1449 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001450
1451 return args;
1452}
1453
chaviwd1c23182019-12-20 18:44:56 -08001454static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1455 const std::vector<PointF>& points) {
1456 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001457 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1458 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1459 }
1460
chaviwd1c23182019-12-20 18:44:56 -08001461 PointerProperties pointerProperties[pointerCount];
1462 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001463
chaviwd1c23182019-12-20 18:44:56 -08001464 for (size_t i = 0; i < pointerCount; i++) {
1465 pointerProperties[i].clear();
1466 pointerProperties[i].id = i;
1467 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001468
chaviwd1c23182019-12-20 18:44:56 -08001469 pointerCoords[i].clear();
1470 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1471 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1472 }
Jackal Guof9696682018-10-05 12:23:23 +08001473
1474 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1475 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001476 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001477 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1478 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001479 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1480 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001481 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1482 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001483
1484 return args;
1485}
1486
chaviwd1c23182019-12-20 18:44:56 -08001487static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1488 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1489}
1490
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001491static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1492 const PointerCaptureRequest& request) {
1493 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001494}
1495
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001496/**
1497 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1498 * broken channel.
1499 */
1500TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1501 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1502 sp<FakeWindowHandle> window =
1503 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1504 ADISPLAY_ID_DEFAULT);
1505
1506 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1507
1508 // Window closes its channel, but the window remains.
1509 window->destroyReceiver();
1510 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1511}
1512
Arthur Hungb92218b2018-08-14 12:00:21 +08001513TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001514 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001515 sp<FakeWindowHandle> window =
1516 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001517
Arthur Hung72d8dc32020-03-28 00:48:39 +00001518 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001519 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1520 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1521 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001522
1523 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001524 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001525}
1526
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001527TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1528 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1529 sp<FakeWindowHandle> window =
1530 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1531
1532 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1533 // Inject a MotionEvent to an unknown display.
1534 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1535 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1536 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1537
1538 // Window should receive motion event.
1539 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1540}
1541
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001542/**
1543 * Calling setInputWindows once with FLAG_NOT_TOUCH_MODAL should not cause any issues.
1544 * To ensure that window receives only events that were directly inside of it, add
1545 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1546 * when finding touched windows.
1547 * This test serves as a sanity check for the next test, where setInputWindows is
1548 * called twice.
1549 */
1550TEST_F(InputDispatcherTest, SetInputWindowOnce_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001551 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001552 sp<FakeWindowHandle> window =
1553 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1554 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001555 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001556
1557 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001558 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001559 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1560 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001561 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001562
1563 // Window should receive motion event.
1564 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1565}
1566
1567/**
1568 * Calling setInputWindows twice, with the same info, should not cause any issues.
1569 * To ensure that window receives only events that were directly inside of it, add
1570 * FLAG_NOT_TOUCH_MODAL. This will enforce using the touchableRegion of the input
1571 * when finding touched windows.
1572 */
1573TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001574 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001575 sp<FakeWindowHandle> window =
1576 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1577 window->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05001578 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001579
1580 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1581 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001582 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001583 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1584 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001585 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001586
1587 // Window should receive motion event.
1588 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1589}
1590
Arthur Hungb92218b2018-08-14 12:00:21 +08001591// The foreground window should receive the first touch down event.
1592TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001593 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001594 sp<FakeWindowHandle> windowTop =
1595 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1596 sp<FakeWindowHandle> windowSecond =
1597 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001598
Arthur Hung72d8dc32020-03-28 00:48:39 +00001599 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001600 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1601 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1602 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001603
1604 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001605 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001606 windowSecond->assertNoEvents();
1607}
1608
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001609/**
1610 * Two windows: A top window, and a wallpaper behind the window.
1611 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1612 * gets ACTION_CANCEL.
1613 * 1. foregroundWindow <-- has wallpaper (hasWallpaper=true)
1614 * 2. wallpaperWindow <-- is wallpaper (type=InputWindowInfo::Type::WALLPAPER)
1615 */
1616TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1617 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1618 sp<FakeWindowHandle> foregroundWindow =
1619 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1620 foregroundWindow->setHasWallpaper(true);
1621 sp<FakeWindowHandle> wallpaperWindow =
1622 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1623 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1624 constexpr int expectedWallpaperFlags =
1625 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1626
1627 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1628 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1629 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1630 {100, 200}))
1631 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1632
1633 // Both foreground window and its wallpaper should receive the touch down
1634 foregroundWindow->consumeMotionDown();
1635 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1636
1637 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1638 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1639 ADISPLAY_ID_DEFAULT, {110, 200}))
1640 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1641
1642 foregroundWindow->consumeMotionMove();
1643 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1644
1645 // Now the foreground window goes away, but the wallpaper stays
1646 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1647 foregroundWindow->consumeMotionCancel();
1648 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1649 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1650}
1651
1652/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001653 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1654 * with the following differences:
1655 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1656 * clean up the connection.
1657 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1658 * Ensure that there's no crash in the dispatcher.
1659 */
1660TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1661 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1662 sp<FakeWindowHandle> foregroundWindow =
1663 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
1664 foregroundWindow->setHasWallpaper(true);
1665 sp<FakeWindowHandle> wallpaperWindow =
1666 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1667 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1668 constexpr int expectedWallpaperFlags =
1669 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1670
1671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1672 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1673 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1674 {100, 200}))
1675 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1676
1677 // Both foreground window and its wallpaper should receive the touch down
1678 foregroundWindow->consumeMotionDown();
1679 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1680
1681 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1682 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1683 ADISPLAY_ID_DEFAULT, {110, 200}))
1684 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1685
1686 foregroundWindow->consumeMotionMove();
1687 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1688
1689 // Wallpaper closes its channel, but the window remains.
1690 wallpaperWindow->destroyReceiver();
1691 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1692
1693 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1694 // is no longer valid.
1695 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1696 foregroundWindow->consumeMotionCancel();
1697}
1698
1699/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001700 * A single window that receives touch (on top), and a wallpaper window underneath it.
1701 * The top window gets a multitouch gesture.
1702 * Ensure that wallpaper gets the same gesture.
1703 */
1704TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1705 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1706 sp<FakeWindowHandle> window =
1707 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1708 window->setHasWallpaper(true);
1709
1710 sp<FakeWindowHandle> wallpaperWindow =
1711 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1712 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1713 constexpr int expectedWallpaperFlags =
1714 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1715
1716 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1717
1718 // Touch down on top window
1719 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1720 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1721 {100, 100}))
1722 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1723
1724 // Both top window and its wallpaper should receive the touch down
1725 window->consumeMotionDown();
1726 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1727
1728 // Second finger down on the top window
1729 const MotionEvent secondFingerDownEvent =
1730 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1731 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1732 AINPUT_SOURCE_TOUCHSCREEN)
1733 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1734 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1735 .x(100)
1736 .y(100))
1737 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1738 .x(150)
1739 .y(150))
1740 .build();
1741 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1742 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1743 InputEventInjectionSync::WAIT_FOR_RESULT))
1744 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1745
1746 window->consumeMotionPointerDown(1 /* pointerIndex */);
1747 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1748 expectedWallpaperFlags);
1749 window->assertNoEvents();
1750 wallpaperWindow->assertNoEvents();
1751}
1752
1753/**
1754 * Two windows: a window on the left and window on the right.
1755 * A third window, wallpaper, is behind both windows, and spans both top windows.
1756 * The first touch down goes to the left window. A second pointer touches down on the right window.
1757 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1758 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1759 * ACTION_POINTER_DOWN(1).
1760 */
1761TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1762 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1763 sp<FakeWindowHandle> leftWindow =
1764 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1765 leftWindow->setFrame(Rect(0, 0, 200, 200));
1766 leftWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1767 leftWindow->setHasWallpaper(true);
1768
1769 sp<FakeWindowHandle> rightWindow =
1770 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1771 rightWindow->setFrame(Rect(200, 0, 400, 200));
1772 rightWindow->setFlags(WindowInfo::Flag::SPLIT_TOUCH | WindowInfo::Flag::NOT_TOUCH_MODAL);
1773 rightWindow->setHasWallpaper(true);
1774
1775 sp<FakeWindowHandle> wallpaperWindow =
1776 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1777 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
1778 wallpaperWindow->setType(WindowInfo::Type::WALLPAPER);
1779 constexpr int expectedWallpaperFlags =
1780 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1781
1782 mDispatcher->setInputWindows(
1783 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1784
1785 // Touch down on left window
1786 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1787 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1788 {100, 100}))
1789 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1790
1791 // Both foreground window and its wallpaper should receive the touch down
1792 leftWindow->consumeMotionDown();
1793 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1794
1795 // Second finger down on the right window
1796 const MotionEvent secondFingerDownEvent =
1797 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
1798 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
1799 AINPUT_SOURCE_TOUCHSCREEN)
1800 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1801 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1802 .x(100)
1803 .y(100))
1804 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1805 .x(300)
1806 .y(100))
1807 .build();
1808 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1809 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1810 InputEventInjectionSync::WAIT_FOR_RESULT))
1811 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1812
1813 leftWindow->consumeMotionMove();
1814 // Since the touch is split, right window gets ACTION_DOWN
1815 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1816 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1817 expectedWallpaperFlags);
1818
1819 // Now, leftWindow, which received the first finger, disappears.
1820 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1821 leftWindow->consumeMotionCancel();
1822 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1823 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1824
1825 // The pointer that's still down on the right window moves, and goes to the right window only.
1826 // As far as the dispatcher's concerned though, both pointers are still present.
1827 const MotionEvent secondFingerMoveEvent =
1828 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1829 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1830 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1831 .x(100)
1832 .y(100))
1833 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1834 .x(310)
1835 .y(110))
1836 .build();
1837 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1838 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1839 InputEventInjectionSync::WAIT_FOR_RESULT));
1840 rightWindow->consumeMotionMove();
1841
1842 leftWindow->assertNoEvents();
1843 rightWindow->assertNoEvents();
1844 wallpaperWindow->assertNoEvents();
1845}
1846
Garfield Tandf26e862020-07-01 20:18:19 -07001847TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001848 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001849 sp<FakeWindowHandle> windowLeft =
1850 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1851 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05001852 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001853 sp<FakeWindowHandle> windowRight =
1854 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1855 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001856 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001857
1858 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1859
1860 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1861
1862 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001863 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001864 injectMotionEvent(mDispatcher,
1865 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1866 AINPUT_SOURCE_MOUSE)
1867 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1868 .x(900)
1869 .y(400))
1870 .build()));
1871 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1872 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1873 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1874 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1875
1876 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001877 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001878 injectMotionEvent(mDispatcher,
1879 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1880 AINPUT_SOURCE_MOUSE)
1881 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1882 .x(300)
1883 .y(400))
1884 .build()));
1885 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1886 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1887 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1888 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1889 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1890 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1891
1892 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001893 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001894 injectMotionEvent(mDispatcher,
1895 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1896 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1897 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1898 .x(300)
1899 .y(400))
1900 .build()));
1901 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1902
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001903 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001904 injectMotionEvent(mDispatcher,
1905 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
1906 AINPUT_SOURCE_MOUSE)
1907 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1908 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1909 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1910 .x(300)
1911 .y(400))
1912 .build()));
1913 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
1914 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1915
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001916 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001917 injectMotionEvent(mDispatcher,
1918 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1919 AINPUT_SOURCE_MOUSE)
1920 .buttonState(0)
1921 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1922 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1923 .x(300)
1924 .y(400))
1925 .build()));
1926 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
1927 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1928
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001929 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001930 injectMotionEvent(mDispatcher,
1931 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
1932 .buttonState(0)
1933 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1934 .x(300)
1935 .y(400))
1936 .build()));
1937 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
1938
1939 // Move mouse cursor back to right window
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_HOVER_MOVE,
1943 AINPUT_SOURCE_MOUSE)
1944 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1945 .x(900)
1946 .y(400))
1947 .build()));
1948 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1949 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1950 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1951 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1952 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1953 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1954}
1955
1956// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
1957// directly in this test.
1958TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001959 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001960 sp<FakeWindowHandle> window =
1961 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
1962 window->setFrame(Rect(0, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05001963 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tandf26e862020-07-01 20:18:19 -07001964
1965 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1966
1967 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1968
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001969 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001970 injectMotionEvent(mDispatcher,
1971 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
1972 AINPUT_SOURCE_MOUSE)
1973 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1974 .x(300)
1975 .y(400))
1976 .build()));
1977 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1978 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1979
1980 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001981 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001982 injectMotionEvent(mDispatcher,
1983 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1984 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1985 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1986 .x(300)
1987 .y(400))
1988 .build()));
1989 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1990
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_BUTTON_PRESS,
1994 AINPUT_SOURCE_MOUSE)
1995 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1996 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
1997 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1998 .x(300)
1999 .y(400))
2000 .build()));
2001 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2002 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2003
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002004 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002005 injectMotionEvent(mDispatcher,
2006 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2007 AINPUT_SOURCE_MOUSE)
2008 .buttonState(0)
2009 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2010 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2011 .x(300)
2012 .y(400))
2013 .build()));
2014 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2015 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2016
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002017 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002018 injectMotionEvent(mDispatcher,
2019 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2020 .buttonState(0)
2021 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2022 .x(300)
2023 .y(400))
2024 .build()));
2025 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
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_HOVER_EXIT,
2030 AINPUT_SOURCE_MOUSE)
2031 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2032 .x(300)
2033 .y(400))
2034 .build()));
2035 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2036 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2037}
2038
Garfield Tan00f511d2019-06-12 16:55:40 -07002039TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002040 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002041
2042 sp<FakeWindowHandle> windowLeft =
2043 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2044 windowLeft->setFrame(Rect(0, 0, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002045 windowLeft->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002046 sp<FakeWindowHandle> windowRight =
2047 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2048 windowRight->setFrame(Rect(600, 0, 1200, 800));
chaviw3277faf2021-05-19 16:45:23 -05002049 windowRight->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Garfield Tan00f511d2019-06-12 16:55:40 -07002050
2051 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2052
Arthur Hung72d8dc32020-03-28 00:48:39 +00002053 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002054
2055 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2056 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002057 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002058 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002059 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002060 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002061 windowRight->assertNoEvents();
2062}
2063
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002064TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002065 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002066 sp<FakeWindowHandle> window =
2067 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002068 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002069
Arthur Hung72d8dc32020-03-28 00:48:39 +00002070 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002071 setFocusedWindow(window);
2072
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002073 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002074
2075 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2076 mDispatcher->notifyKey(&keyArgs);
2077
2078 // Window should receive key down event.
2079 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2080
2081 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2082 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002083 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002084 mDispatcher->notifyDeviceReset(&args);
2085 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2086 AKEY_EVENT_FLAG_CANCELED);
2087}
2088
2089TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002090 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002091 sp<FakeWindowHandle> window =
2092 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2093
Arthur Hung72d8dc32020-03-28 00:48:39 +00002094 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002095
2096 NotifyMotionArgs motionArgs =
2097 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2098 ADISPLAY_ID_DEFAULT);
2099 mDispatcher->notifyMotion(&motionArgs);
2100
2101 // Window should receive motion down event.
2102 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2103
2104 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2105 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002106 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002107 mDispatcher->notifyDeviceReset(&args);
2108 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2109 0 /*expectedFlags*/);
2110}
2111
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002112/**
2113 * Ensure the correct coordinate spaces are used by InputDispatcher.
2114 *
2115 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2116 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2117 * space.
2118 */
2119class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2120public:
2121 void SetUp() override {
2122 InputDispatcherTest::SetUp();
2123 mDisplayInfos.clear();
2124 mWindowInfos.clear();
2125 }
2126
2127 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2128 gui::DisplayInfo info;
2129 info.displayId = displayId;
2130 info.transform = transform;
2131 mDisplayInfos.push_back(std::move(info));
2132 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2133 }
2134
2135 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2136 mWindowInfos.push_back(*windowHandle->getInfo());
2137 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2138 }
2139
2140 // Set up a test scenario where the display has a scaled projection and there are two windows
2141 // on the display.
2142 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2143 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2144 // respectively.
2145 ui::Transform displayTransform;
2146 displayTransform.set(2, 0, 0, 4);
2147 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2148
2149 std::shared_ptr<FakeApplicationHandle> application =
2150 std::make_shared<FakeApplicationHandle>();
2151
2152 // Add two windows to the display. Their frames are represented in the display space.
2153 sp<FakeWindowHandle> firstWindow =
2154 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2155 firstWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2156 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2157 addWindow(firstWindow);
2158
2159 sp<FakeWindowHandle> secondWindow =
2160 new FakeWindowHandle(application, mDispatcher, "Second Window",
2161 ADISPLAY_ID_DEFAULT);
2162 secondWindow->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2163 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2164 addWindow(secondWindow);
2165 return {std::move(firstWindow), std::move(secondWindow)};
2166 }
2167
2168private:
2169 std::vector<gui::DisplayInfo> mDisplayInfos;
2170 std::vector<gui::WindowInfo> mWindowInfos;
2171};
2172
2173TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2174 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2175 // Send down to the first window. The point is represented in the display space. The point is
2176 // selected so that if the hit test was done with the transform applied to it, then it would
2177 // end up in the incorrect window.
2178 NotifyMotionArgs downMotionArgs =
2179 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2180 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2181 mDispatcher->notifyMotion(&downMotionArgs);
2182
2183 firstWindow->consumeMotionDown();
2184 secondWindow->assertNoEvents();
2185}
2186
2187// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2188// the event should be treated as being in the logical display space.
2189TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2190 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2191 // Send down to the first window. The point is represented in the logical display space. The
2192 // point is selected so that if the hit test was done in logical display space, then it would
2193 // end up in the incorrect window.
2194 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2195 PointF{75 * 2, 55 * 4});
2196
2197 firstWindow->consumeMotionDown();
2198 secondWindow->assertNoEvents();
2199}
2200
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002201// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2202// event should be treated as being in the logical display space.
2203TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2204 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2205
2206 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2207 ui::Transform injectedEventTransform;
2208 injectedEventTransform.set(matrix);
2209 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2210 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2211
2212 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2213 .displayId(ADISPLAY_ID_DEFAULT)
2214 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2215 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2216 .x(untransformedPoint.x)
2217 .y(untransformedPoint.y))
2218 .build();
2219 event.transform(matrix);
2220
2221 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2222 InputEventInjectionSync::WAIT_FOR_RESULT);
2223
2224 firstWindow->consumeMotionDown();
2225 secondWindow->assertNoEvents();
2226}
2227
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002228TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2229 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2230
2231 // Send down to the second window.
2232 NotifyMotionArgs downMotionArgs =
2233 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2234 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2235 mDispatcher->notifyMotion(&downMotionArgs);
2236
2237 firstWindow->assertNoEvents();
2238 const MotionEvent* event = secondWindow->consumeMotion();
2239 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2240
2241 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2242 EXPECT_EQ(300, event->getRawX(0));
2243 EXPECT_EQ(880, event->getRawY(0));
2244
2245 // Ensure that the x and y values are in the window's coordinate space.
2246 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2247 // the logical display space. This will be the origin of the window space.
2248 EXPECT_EQ(100, event->getX(0));
2249 EXPECT_EQ(80, event->getY(0));
2250}
2251
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002252using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2253 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002254
2255class TransferTouchFixture : public InputDispatcherTest,
2256 public ::testing::WithParamInterface<TransferFunction> {};
2257
2258TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002259 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002260
2261 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002262 sp<FakeWindowHandle> firstWindow =
2263 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2264 sp<FakeWindowHandle> secondWindow =
2265 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002266
2267 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002268 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002269
2270 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002271 NotifyMotionArgs downMotionArgs =
2272 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2273 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002274 mDispatcher->notifyMotion(&downMotionArgs);
2275 // Only the first window should get the down event
2276 firstWindow->consumeMotionDown();
2277 secondWindow->assertNoEvents();
2278
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002279 // Transfer touch to the second window
2280 TransferFunction f = GetParam();
2281 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2282 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002283 // The first window gets cancel and the second gets down
2284 firstWindow->consumeMotionCancel();
2285 secondWindow->consumeMotionDown();
2286
2287 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002288 NotifyMotionArgs upMotionArgs =
2289 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2290 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002291 mDispatcher->notifyMotion(&upMotionArgs);
2292 // The first window gets no events and the second gets up
2293 firstWindow->assertNoEvents();
2294 secondWindow->consumeMotionUp();
2295}
2296
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002297TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002298 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002299
2300 PointF touchPoint = {10, 10};
2301
2302 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002303 sp<FakeWindowHandle> firstWindow =
2304 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2305 sp<FakeWindowHandle> secondWindow =
2306 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002307
2308 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002309 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002310
2311 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002312 NotifyMotionArgs downMotionArgs =
2313 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2314 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002315 mDispatcher->notifyMotion(&downMotionArgs);
2316 // Only the first window should get the down event
2317 firstWindow->consumeMotionDown();
2318 secondWindow->assertNoEvents();
2319
2320 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002321 NotifyMotionArgs pointerDownMotionArgs =
2322 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2323 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2324 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2325 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002326 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2327 // Only the first window should get the pointer down event
2328 firstWindow->consumeMotionPointerDown(1);
2329 secondWindow->assertNoEvents();
2330
2331 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002332 TransferFunction f = GetParam();
2333 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2334 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002335 // The first window gets cancel and the second gets down and pointer down
2336 firstWindow->consumeMotionCancel();
2337 secondWindow->consumeMotionDown();
2338 secondWindow->consumeMotionPointerDown(1);
2339
2340 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002341 NotifyMotionArgs pointerUpMotionArgs =
2342 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2343 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2344 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2345 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002346 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2347 // The first window gets nothing and the second gets pointer up
2348 firstWindow->assertNoEvents();
2349 secondWindow->consumeMotionPointerUp(1);
2350
2351 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002352 NotifyMotionArgs upMotionArgs =
2353 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2354 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002355 mDispatcher->notifyMotion(&upMotionArgs);
2356 // The first window gets nothing and the second gets up
2357 firstWindow->assertNoEvents();
2358 secondWindow->consumeMotionUp();
2359}
2360
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002361// For the cases of single pointer touch and two pointers non-split touch, the api's
2362// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2363// for the case where there are multiple pointers split across several windows.
2364INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2365 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002366 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2367 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002368 return dispatcher->transferTouch(destChannelToken);
2369 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002370 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2371 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002372 return dispatcher->transferTouchFocus(from, to,
2373 false /*isDragAndDrop*/);
2374 }));
2375
Svet Ganov5d3bc372020-01-26 23:11:07 -08002376TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002377 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002378
2379 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002380 sp<FakeWindowHandle> firstWindow =
2381 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002382 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002383 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002384
2385 // Create a non touch modal window that supports split touch
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002386 sp<FakeWindowHandle> secondWindow =
2387 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002388 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002389 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002390
2391 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002392 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002393
2394 PointF pointInFirst = {300, 200};
2395 PointF pointInSecond = {300, 600};
2396
2397 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002398 NotifyMotionArgs firstDownMotionArgs =
2399 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2400 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002401 mDispatcher->notifyMotion(&firstDownMotionArgs);
2402 // Only the first window should get the down event
2403 firstWindow->consumeMotionDown();
2404 secondWindow->assertNoEvents();
2405
2406 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002407 NotifyMotionArgs secondDownMotionArgs =
2408 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2409 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2410 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2411 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002412 mDispatcher->notifyMotion(&secondDownMotionArgs);
2413 // The first window gets a move and the second a down
2414 firstWindow->consumeMotionMove();
2415 secondWindow->consumeMotionDown();
2416
2417 // Transfer touch focus to the second window
2418 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2419 // The first window gets cancel and the new gets pointer down (it already saw down)
2420 firstWindow->consumeMotionCancel();
2421 secondWindow->consumeMotionPointerDown(1);
2422
2423 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002424 NotifyMotionArgs pointerUpMotionArgs =
2425 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2426 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2427 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2428 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002429 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2430 // The first window gets nothing and the second gets pointer up
2431 firstWindow->assertNoEvents();
2432 secondWindow->consumeMotionPointerUp(1);
2433
2434 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002435 NotifyMotionArgs upMotionArgs =
2436 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2437 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002438 mDispatcher->notifyMotion(&upMotionArgs);
2439 // The first window gets nothing and the second gets up
2440 firstWindow->assertNoEvents();
2441 secondWindow->consumeMotionUp();
2442}
2443
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002444// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2445// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2446// touch is not supported, so the touch should continue on those windows and the transferred-to
2447// window should get nothing.
2448TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2449 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2450
2451 // Create a non touch modal window that supports split touch
2452 sp<FakeWindowHandle> firstWindow =
2453 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2454 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002455 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002456
2457 // Create a non touch modal window that supports split touch
2458 sp<FakeWindowHandle> secondWindow =
2459 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2460 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002461 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
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));
2526 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2527 sp<FakeWindowHandle> secondWindowInPrimary =
2528 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2529 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2530 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2531
2532 sp<FakeWindowHandle> mirrorWindowInPrimary =
2533 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2534 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2535 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2536
2537 sp<FakeWindowHandle> firstWindowInSecondary =
2538 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2539 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2540 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2541
2542 sp<FakeWindowHandle> secondWindowInSecondary =
2543 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2544 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2545 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2546
2547 // Update window info, let it find window handle of second display first.
2548 mDispatcher->setInputWindows(
2549 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2550 {ADISPLAY_ID_DEFAULT,
2551 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2552
2553 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2554 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2555 {50, 50}))
2556 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2557
2558 // Window should receive motion event.
2559 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2560
2561 // Transfer touch focus
2562 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2563 secondWindowInPrimary->getToken()));
2564 // The first window gets cancel.
2565 firstWindowInPrimary->consumeMotionCancel();
2566 secondWindowInPrimary->consumeMotionDown();
2567
2568 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2569 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2570 ADISPLAY_ID_DEFAULT, {150, 50}))
2571 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2572 firstWindowInPrimary->assertNoEvents();
2573 secondWindowInPrimary->consumeMotionMove();
2574
2575 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2576 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2577 {150, 50}))
2578 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2579 firstWindowInPrimary->assertNoEvents();
2580 secondWindowInPrimary->consumeMotionUp();
2581}
2582
2583// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2584// 'transferTouch' api.
2585TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2586 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2587 sp<FakeWindowHandle> firstWindowInPrimary =
2588 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2589 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
2590 firstWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2591 sp<FakeWindowHandle> secondWindowInPrimary =
2592 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2593 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2594 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2595
2596 sp<FakeWindowHandle> mirrorWindowInPrimary =
2597 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2598 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
2599 mirrorWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2600
2601 sp<FakeWindowHandle> firstWindowInSecondary =
2602 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2603 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
2604 firstWindowInSecondary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2605
2606 sp<FakeWindowHandle> secondWindowInSecondary =
2607 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2608 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
2609 secondWindowInPrimary->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
2610
2611 // Update window info, let it find window handle of second display first.
2612 mDispatcher->setInputWindows(
2613 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2614 {ADISPLAY_ID_DEFAULT,
2615 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2616
2617 // Touch on second display.
2618 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2619 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2620 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2621
2622 // Window should receive motion event.
2623 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2624
2625 // Transfer touch focus
2626 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2627
2628 // The first window gets cancel.
2629 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2630 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2631
2632 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2633 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2634 SECOND_DISPLAY_ID, {150, 50}))
2635 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2636 firstWindowInPrimary->assertNoEvents();
2637 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2638
2639 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2640 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2641 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2642 firstWindowInPrimary->assertNoEvents();
2643 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2644}
2645
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002646TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002647 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002648 sp<FakeWindowHandle> window =
2649 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2650
Vishnu Nair47074b82020-08-14 11:54:47 -07002651 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002652 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002653 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002654
2655 window->consumeFocusEvent(true);
2656
2657 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2658 mDispatcher->notifyKey(&keyArgs);
2659
2660 // Window should receive key down event.
2661 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2662}
2663
2664TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002665 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002666 sp<FakeWindowHandle> window =
2667 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2668
Arthur Hung72d8dc32020-03-28 00:48:39 +00002669 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002670
2671 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2672 mDispatcher->notifyKey(&keyArgs);
2673 mDispatcher->waitForIdle();
2674
2675 window->assertNoEvents();
2676}
2677
2678// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2679TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002680 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002681 sp<FakeWindowHandle> window =
2682 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2683
Arthur Hung72d8dc32020-03-28 00:48:39 +00002684 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002685
2686 // Send key
2687 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2688 mDispatcher->notifyKey(&keyArgs);
2689 // Send motion
2690 NotifyMotionArgs motionArgs =
2691 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2692 ADISPLAY_ID_DEFAULT);
2693 mDispatcher->notifyMotion(&motionArgs);
2694
2695 // Window should receive only the motion event
2696 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2697 window->assertNoEvents(); // Key event or focus event will not be received
2698}
2699
arthurhungea3f4fc2020-12-21 23:18:53 +08002700TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2701 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2702
2703 // Create first non touch modal window that supports split touch
2704 sp<FakeWindowHandle> firstWindow =
2705 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2706 firstWindow->setFrame(Rect(0, 0, 600, 400));
chaviw3277faf2021-05-19 16:45:23 -05002707 firstWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002708
2709 // Create second non touch modal window that supports split touch
2710 sp<FakeWindowHandle> secondWindow =
2711 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2712 secondWindow->setFrame(Rect(0, 400, 600, 800));
chaviw3277faf2021-05-19 16:45:23 -05002713 secondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
arthurhungea3f4fc2020-12-21 23:18:53 +08002714
2715 // Add the windows to the dispatcher
2716 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2717
2718 PointF pointInFirst = {300, 200};
2719 PointF pointInSecond = {300, 600};
2720
2721 // Send down to the first window
2722 NotifyMotionArgs firstDownMotionArgs =
2723 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2724 ADISPLAY_ID_DEFAULT, {pointInFirst});
2725 mDispatcher->notifyMotion(&firstDownMotionArgs);
2726 // Only the first window should get the down event
2727 firstWindow->consumeMotionDown();
2728 secondWindow->assertNoEvents();
2729
2730 // Send down to the second window
2731 NotifyMotionArgs secondDownMotionArgs =
2732 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_DOWN |
2733 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2734 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2735 {pointInFirst, pointInSecond});
2736 mDispatcher->notifyMotion(&secondDownMotionArgs);
2737 // The first window gets a move and the second a down
2738 firstWindow->consumeMotionMove();
2739 secondWindow->consumeMotionDown();
2740
2741 // Send pointer cancel to the second window
2742 NotifyMotionArgs pointerUpMotionArgs =
2743 generateMotionArgs(AMOTION_EVENT_ACTION_POINTER_UP |
2744 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
2745 AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2746 {pointInFirst, pointInSecond});
2747 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2748 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2749 // The first window gets move and the second gets cancel.
2750 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2751 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2752
2753 // Send up event.
2754 NotifyMotionArgs upMotionArgs =
2755 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2756 ADISPLAY_ID_DEFAULT);
2757 mDispatcher->notifyMotion(&upMotionArgs);
2758 // The first window gets up and the second gets nothing.
2759 firstWindow->consumeMotionUp();
2760 secondWindow->assertNoEvents();
2761}
2762
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002763TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2764 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2765
2766 sp<FakeWindowHandle> window =
2767 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2768 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2769 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2770 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2771 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2772
2773 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2774 window->assertNoEvents();
2775 mDispatcher->waitForIdle();
2776}
2777
chaviwd1c23182019-12-20 18:44:56 -08002778class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002779public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002780 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002781 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07002782 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002783 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002784 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002785 }
2786
chaviwd1c23182019-12-20 18:44:56 -08002787 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2788
2789 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2790 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2791 expectedDisplayId, expectedFlags);
2792 }
2793
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002794 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2795
2796 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2797
chaviwd1c23182019-12-20 18:44:56 -08002798 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2799 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2800 expectedDisplayId, expectedFlags);
2801 }
2802
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002803 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2804 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2805 expectedDisplayId, expectedFlags);
2806 }
2807
chaviwd1c23182019-12-20 18:44:56 -08002808 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2809 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2810 expectedDisplayId, expectedFlags);
2811 }
2812
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002813 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2814 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2815 expectedDisplayId, expectedFlags);
2816 }
2817
Arthur Hungfbfa5722021-11-16 02:45:54 +00002818 void consumeMotionPointerDown(int32_t pointerIdx) {
2819 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2820 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2821 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2822 0 /*expectedFlags*/);
2823 }
2824
Evan Rosky84f07f02021-04-16 10:42:42 -07002825 MotionEvent* consumeMotion() {
2826 InputEvent* event = mInputReceiver->consume();
2827 if (!event) {
2828 ADD_FAILURE() << "No event was produced";
2829 return nullptr;
2830 }
2831 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2832 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2833 return nullptr;
2834 }
2835 return static_cast<MotionEvent*>(event);
2836 }
2837
chaviwd1c23182019-12-20 18:44:56 -08002838 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2839
2840private:
2841 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002842};
2843
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002844using InputDispatcherMonitorTest = InputDispatcherTest;
2845
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002846/**
2847 * Two entities that receive touch: A window, and a global monitor.
2848 * The touch goes to the window, and then the window disappears.
2849 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2850 * for the monitor, as well.
2851 * 1. foregroundWindow
2852 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2853 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002854TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002855 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2856 sp<FakeWindowHandle> window =
2857 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2858
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002859 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002860
2861 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2862 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2863 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2864 {100, 200}))
2865 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2866
2867 // Both the foreground window and the global monitor should receive the touch down
2868 window->consumeMotionDown();
2869 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2870
2871 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2872 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2873 ADISPLAY_ID_DEFAULT, {110, 200}))
2874 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2875
2876 window->consumeMotionMove();
2877 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2878
2879 // Now the foreground window goes away
2880 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2881 window->consumeMotionCancel();
2882 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2883
2884 // If more events come in, there will be no more foreground window to send them to. This will
2885 // cause a cancel for the monitor, as well.
2886 ASSERT_EQ(InputEventInjectionResult::FAILED,
2887 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2888 ADISPLAY_ID_DEFAULT, {120, 200}))
2889 << "Injection should fail because the window was removed";
2890 window->assertNoEvents();
2891 // Global monitor now gets the cancel
2892 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2893}
2894
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002895TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002896 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002897 sp<FakeWindowHandle> window =
2898 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002899 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002900
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002901 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002902
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002903 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002904 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002905 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00002906 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08002907 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002908}
2909
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002910TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
2911 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002912
Chris Yea209fde2020-07-22 13:54:51 -07002913 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002914 sp<FakeWindowHandle> window =
2915 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002916 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002917
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002918 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00002919 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002920 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08002921 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002922 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002923
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002924 // Pilfer pointers from the monitor.
2925 // This should not do anything and the window should continue to receive events.
2926 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00002927
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002928 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002929 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2930 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002931 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002932
2933 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2934 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002935}
2936
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002937TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07002938 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2939 sp<FakeWindowHandle> window =
2940 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2941 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2942 window->setWindowOffset(20, 40);
2943 window->setWindowTransform(0, 1, -1, 0);
2944
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002945 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07002946
2947 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2948 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
2949 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2950 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2951 MotionEvent* event = monitor.consumeMotion();
2952 // Even though window has transform, gesture monitor must not.
2953 ASSERT_EQ(ui::Transform(), event->getTransform());
2954}
2955
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002956TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00002957 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002958 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00002959
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002960 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00002961 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002962 << "Injection should fail if there is a monitor, but no touchable window";
2963 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00002964}
2965
chaviw81e2bb92019-12-18 15:03:51 -08002966TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002967 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08002968 sp<FakeWindowHandle> window =
2969 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2970
Arthur Hung72d8dc32020-03-28 00:48:39 +00002971 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08002972
2973 NotifyMotionArgs motionArgs =
2974 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2975 ADISPLAY_ID_DEFAULT);
2976
2977 mDispatcher->notifyMotion(&motionArgs);
2978 // Window should receive motion down event.
2979 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2980
2981 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002982 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08002983 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
2984 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2985 motionArgs.pointerCoords[0].getX() - 10);
2986
2987 mDispatcher->notifyMotion(&motionArgs);
2988 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
2989 0 /*expectedFlags*/);
2990}
2991
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002992/**
2993 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
2994 * the device default right away. In the test scenario, we check both the default value,
2995 * and the action of enabling / disabling.
2996 */
2997TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07002998 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002999 sp<FakeWindowHandle> window =
3000 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003001 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003002
3003 // Set focused application.
3004 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003005 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003006
3007 SCOPED_TRACE("Check default value of touch mode");
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*/, true /*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*/, true /*inTouchMode*/);
3016
3017 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003018 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3019 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003020 window->consumeTouchModeEvent(false);
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*/, false /*inTouchMode*/);
3025
3026 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003027 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003028 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003029 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3030
3031 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003032 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3033 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003034 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003035 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003036 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003037 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003038 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3039
3040 window->assertNoEvents();
3041}
3042
Gang Wange9087892020-01-07 12:17:14 -05003043TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003044 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003045 sp<FakeWindowHandle> window =
3046 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3047
3048 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003049 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003050
Arthur Hung72d8dc32020-03-28 00:48:39 +00003051 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003052 setFocusedWindow(window);
3053
Gang Wange9087892020-01-07 12:17:14 -05003054 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3055
3056 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3057 mDispatcher->notifyKey(&keyArgs);
3058
3059 InputEvent* event = window->consume();
3060 ASSERT_NE(event, nullptr);
3061
3062 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3063 ASSERT_NE(verified, nullptr);
3064 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3065
3066 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3067 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3068 ASSERT_EQ(keyArgs.source, verified->source);
3069 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3070
3071 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3072
3073 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003074 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003075 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003076 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3077 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3078 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3079 ASSERT_EQ(0, verifiedKey.repeatCount);
3080}
3081
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003082TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003083 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003084 sp<FakeWindowHandle> window =
3085 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3086
3087 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3088
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003089 ui::Transform transform;
3090 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3091
3092 gui::DisplayInfo displayInfo;
3093 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3094 displayInfo.transform = transform;
3095
3096 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003097
3098 NotifyMotionArgs motionArgs =
3099 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3100 ADISPLAY_ID_DEFAULT);
3101 mDispatcher->notifyMotion(&motionArgs);
3102
3103 InputEvent* event = window->consume();
3104 ASSERT_NE(event, nullptr);
3105
3106 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3107 ASSERT_NE(verified, nullptr);
3108 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3109
3110 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3111 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3112 EXPECT_EQ(motionArgs.source, verified->source);
3113 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3114
3115 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3116
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003117 const vec2 rawXY =
3118 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3119 motionArgs.pointerCoords[0].getXYValue());
3120 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3121 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003122 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003123 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003124 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003125 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3126 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3127}
3128
chaviw09c8d2d2020-08-24 15:48:26 -07003129/**
3130 * Ensure that separate calls to sign the same data are generating the same key.
3131 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3132 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3133 * tests.
3134 */
3135TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3136 KeyEvent event = getTestKeyEvent();
3137 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3138
3139 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3140 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3141 ASSERT_EQ(hmac1, hmac2);
3142}
3143
3144/**
3145 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3146 */
3147TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3148 KeyEvent event = getTestKeyEvent();
3149 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3150 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3151
3152 verifiedEvent.deviceId += 1;
3153 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3154
3155 verifiedEvent.source += 1;
3156 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3157
3158 verifiedEvent.eventTimeNanos += 1;
3159 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3160
3161 verifiedEvent.displayId += 1;
3162 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3163
3164 verifiedEvent.action += 1;
3165 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3166
3167 verifiedEvent.downTimeNanos += 1;
3168 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3169
3170 verifiedEvent.flags += 1;
3171 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3172
3173 verifiedEvent.keyCode += 1;
3174 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3175
3176 verifiedEvent.scanCode += 1;
3177 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3178
3179 verifiedEvent.metaState += 1;
3180 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3181
3182 verifiedEvent.repeatCount += 1;
3183 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3184}
3185
Vishnu Nair958da932020-08-21 17:12:37 -07003186TEST_F(InputDispatcherTest, SetFocusedWindow) {
3187 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3188 sp<FakeWindowHandle> windowTop =
3189 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3190 sp<FakeWindowHandle> windowSecond =
3191 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3192 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3193
3194 // Top window is also focusable but is not granted focus.
3195 windowTop->setFocusable(true);
3196 windowSecond->setFocusable(true);
3197 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3198 setFocusedWindow(windowSecond);
3199
3200 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003201 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3202 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003203
3204 // Focused window should receive event.
3205 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3206 windowTop->assertNoEvents();
3207}
3208
3209TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3210 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3211 sp<FakeWindowHandle> window =
3212 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3213 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3214
3215 window->setFocusable(true);
3216 // Release channel for window is no longer valid.
3217 window->releaseChannel();
3218 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3219 setFocusedWindow(window);
3220
3221 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003222 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3223 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003224
3225 // window channel is invalid, so it should not receive any input event.
3226 window->assertNoEvents();
3227}
3228
3229TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3230 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3231 sp<FakeWindowHandle> window =
3232 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3233 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3234
3235 // Window is not focusable.
3236 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3237 setFocusedWindow(window);
3238
3239 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003240 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3241 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003242
3243 // window is invalid, so it should not receive any input event.
3244 window->assertNoEvents();
3245}
3246
3247TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3248 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3249 sp<FakeWindowHandle> windowTop =
3250 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3251 sp<FakeWindowHandle> windowSecond =
3252 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3253 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3254
3255 windowTop->setFocusable(true);
3256 windowSecond->setFocusable(true);
3257 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3258 setFocusedWindow(windowTop);
3259 windowTop->consumeFocusEvent(true);
3260
3261 setFocusedWindow(windowSecond, windowTop);
3262 windowSecond->consumeFocusEvent(true);
3263 windowTop->consumeFocusEvent(false);
3264
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003265 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3266 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003267
3268 // Focused window should receive event.
3269 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3270}
3271
3272TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3273 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3274 sp<FakeWindowHandle> windowTop =
3275 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3276 sp<FakeWindowHandle> windowSecond =
3277 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3278 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3279
3280 windowTop->setFocusable(true);
3281 windowSecond->setFocusable(true);
3282 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3283 setFocusedWindow(windowSecond, windowTop);
3284
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003285 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3286 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003287
3288 // Event should be dropped.
3289 windowTop->assertNoEvents();
3290 windowSecond->assertNoEvents();
3291}
3292
3293TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3294 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3295 sp<FakeWindowHandle> window =
3296 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3297 sp<FakeWindowHandle> previousFocusedWindow =
3298 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3299 ADISPLAY_ID_DEFAULT);
3300 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3301
3302 window->setFocusable(true);
3303 previousFocusedWindow->setFocusable(true);
3304 window->setVisible(false);
3305 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3306 setFocusedWindow(previousFocusedWindow);
3307 previousFocusedWindow->consumeFocusEvent(true);
3308
3309 // Requesting focus on invisible window takes focus from currently focused window.
3310 setFocusedWindow(window);
3311 previousFocusedWindow->consumeFocusEvent(false);
3312
3313 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003314 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003315 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003316 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003317
3318 // Window does not get focus event or key down.
3319 window->assertNoEvents();
3320
3321 // Window becomes visible.
3322 window->setVisible(true);
3323 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3324
3325 // Window receives focus event.
3326 window->consumeFocusEvent(true);
3327 // Focused window receives key down.
3328 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3329}
3330
Vishnu Nair599f1412021-06-21 10:39:58 -07003331TEST_F(InputDispatcherTest, DisplayRemoved) {
3332 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3333 sp<FakeWindowHandle> window =
3334 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3335 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3336
3337 // window is granted focus.
3338 window->setFocusable(true);
3339 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3340 setFocusedWindow(window);
3341 window->consumeFocusEvent(true);
3342
3343 // When a display is removed window loses focus.
3344 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3345 window->consumeFocusEvent(false);
3346}
3347
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003348/**
3349 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3350 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3351 * of the 'slipperyEnterWindow'.
3352 *
3353 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3354 * a way so that the touched location is no longer covered by the top window.
3355 *
3356 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3357 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3358 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3359 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3360 * with ACTION_DOWN).
3361 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3362 * window moved itself away from the touched location and had Flag::SLIPPERY.
3363 *
3364 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3365 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3366 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3367 *
3368 * In this test, we ensure that the event received by the bottom window has
3369 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3370 */
3371TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
3372 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3373 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
3374
3375 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3376 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3377
3378 sp<FakeWindowHandle> slipperyExitWindow =
3379 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviw3277faf2021-05-19 16:45:23 -05003380 slipperyExitWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SLIPPERY);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003381 // Make sure this one overlaps the bottom window
3382 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3383 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3384 // one. Windows with the same owner are not considered to be occluding each other.
3385 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3386
3387 sp<FakeWindowHandle> slipperyEnterWindow =
3388 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3389 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3390
3391 mDispatcher->setInputWindows(
3392 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3393
3394 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3395 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3396 ADISPLAY_ID_DEFAULT, {{50, 50}});
3397 mDispatcher->notifyMotion(&args);
3398 slipperyExitWindow->consumeMotionDown();
3399 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3400 mDispatcher->setInputWindows(
3401 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3402
3403 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3404 ADISPLAY_ID_DEFAULT, {{51, 51}});
3405 mDispatcher->notifyMotion(&args);
3406
3407 slipperyExitWindow->consumeMotionCancel();
3408
3409 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3410 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3411}
3412
Garfield Tan1c7bc862020-01-28 13:24:04 -08003413class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3414protected:
3415 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3416 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3417
Chris Yea209fde2020-07-22 13:54:51 -07003418 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003419 sp<FakeWindowHandle> mWindow;
3420
3421 virtual void SetUp() override {
3422 mFakePolicy = new FakeInputDispatcherPolicy();
3423 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003424 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003425 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3426 ASSERT_EQ(OK, mDispatcher->start());
3427
3428 setUpWindow();
3429 }
3430
3431 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003432 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003433 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3434
Vishnu Nair47074b82020-08-14 11:54:47 -07003435 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003436 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003437 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003438 mWindow->consumeFocusEvent(true);
3439 }
3440
Chris Ye2ad95392020-09-01 13:44:44 -07003441 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003442 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003443 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003444 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3445 mDispatcher->notifyKey(&keyArgs);
3446
3447 // Window should receive key down event.
3448 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3449 }
3450
3451 void expectKeyRepeatOnce(int32_t repeatCount) {
3452 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3453 InputEvent* repeatEvent = mWindow->consume();
3454 ASSERT_NE(nullptr, repeatEvent);
3455
3456 uint32_t eventType = repeatEvent->getType();
3457 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3458
3459 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3460 uint32_t eventAction = repeatKeyEvent->getAction();
3461 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3462 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3463 }
3464
Chris Ye2ad95392020-09-01 13:44:44 -07003465 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003466 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003467 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003468 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3469 mDispatcher->notifyKey(&keyArgs);
3470
3471 // Window should receive key down event.
3472 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3473 0 /*expectedFlags*/);
3474 }
3475};
3476
3477TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003478 sendAndConsumeKeyDown(1 /* deviceId */);
3479 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3480 expectKeyRepeatOnce(repeatCount);
3481 }
3482}
3483
3484TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3485 sendAndConsumeKeyDown(1 /* deviceId */);
3486 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3487 expectKeyRepeatOnce(repeatCount);
3488 }
3489 sendAndConsumeKeyDown(2 /* deviceId */);
3490 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003491 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3492 expectKeyRepeatOnce(repeatCount);
3493 }
3494}
3495
3496TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003497 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003498 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003499 sendAndConsumeKeyUp(1 /* deviceId */);
3500 mWindow->assertNoEvents();
3501}
3502
3503TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3504 sendAndConsumeKeyDown(1 /* deviceId */);
3505 expectKeyRepeatOnce(1 /*repeatCount*/);
3506 sendAndConsumeKeyDown(2 /* deviceId */);
3507 expectKeyRepeatOnce(1 /*repeatCount*/);
3508 // Stale key up from device 1.
3509 sendAndConsumeKeyUp(1 /* deviceId */);
3510 // Device 2 is still down, keep repeating
3511 expectKeyRepeatOnce(2 /*repeatCount*/);
3512 expectKeyRepeatOnce(3 /*repeatCount*/);
3513 // Device 2 key up
3514 sendAndConsumeKeyUp(2 /* deviceId */);
3515 mWindow->assertNoEvents();
3516}
3517
3518TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3519 sendAndConsumeKeyDown(1 /* deviceId */);
3520 expectKeyRepeatOnce(1 /*repeatCount*/);
3521 sendAndConsumeKeyDown(2 /* deviceId */);
3522 expectKeyRepeatOnce(1 /*repeatCount*/);
3523 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3524 sendAndConsumeKeyUp(2 /* deviceId */);
3525 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003526 mWindow->assertNoEvents();
3527}
3528
liushenxiang42232912021-05-21 20:24:09 +08003529TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3530 sendAndConsumeKeyDown(DEVICE_ID);
3531 expectKeyRepeatOnce(1 /*repeatCount*/);
3532 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3533 mDispatcher->notifyDeviceReset(&args);
3534 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3535 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3536 mWindow->assertNoEvents();
3537}
3538
Garfield Tan1c7bc862020-01-28 13:24:04 -08003539TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003540 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003541 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3542 InputEvent* repeatEvent = mWindow->consume();
3543 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3544 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3545 IdGenerator::getSource(repeatEvent->getId()));
3546 }
3547}
3548
3549TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003550 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003551
3552 std::unordered_set<int32_t> idSet;
3553 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3554 InputEvent* repeatEvent = mWindow->consume();
3555 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3556 int32_t id = repeatEvent->getId();
3557 EXPECT_EQ(idSet.end(), idSet.find(id));
3558 idSet.insert(id);
3559 }
3560}
3561
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003562/* Test InputDispatcher for MultiDisplay */
3563class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3564public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003565 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003566 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003567
Chris Yea209fde2020-07-22 13:54:51 -07003568 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003569 windowInPrimary =
3570 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003571
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003572 // Set focus window for primary display, but focused display would be second one.
3573 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003574 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003575 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003576 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003577 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003578
Chris Yea209fde2020-07-22 13:54:51 -07003579 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003580 windowInSecondary =
3581 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003582 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003583 // Set focus display to second one.
3584 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3585 // Set focus window for second display.
3586 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003587 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003588 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003589 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003590 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003591 }
3592
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003593 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003594 InputDispatcherTest::TearDown();
3595
Chris Yea209fde2020-07-22 13:54:51 -07003596 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003597 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003598 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003599 windowInSecondary.clear();
3600 }
3601
3602protected:
Chris Yea209fde2020-07-22 13:54:51 -07003603 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003604 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003605 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003606 sp<FakeWindowHandle> windowInSecondary;
3607};
3608
3609TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3610 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003611 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3612 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3613 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003614 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003615 windowInSecondary->assertNoEvents();
3616
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003617 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003618 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3619 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3620 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003621 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003622 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003623}
3624
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003625TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003626 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003627 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3628 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003629 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003630 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003631 windowInSecondary->assertNoEvents();
3632
3633 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003634 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003635 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003636 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003637 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003638
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003639 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003640 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003641
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003642 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003643 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3644 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003645
3646 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003647 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003648 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003649 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003650 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003651 windowInSecondary->assertNoEvents();
3652}
3653
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003654// Test per-display input monitors for motion event.
3655TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003656 FakeMonitorReceiver monitorInPrimary =
3657 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3658 FakeMonitorReceiver monitorInSecondary =
3659 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003660
3661 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003662 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3663 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3664 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003665 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003666 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003667 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003668 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003669
3670 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003671 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3672 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3673 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003674 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003675 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003676 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003677 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003678
3679 // Test inject a non-pointer motion event.
3680 // If specific a display, it will dispatch to the focused window of particular display,
3681 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003682 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3683 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3684 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003685 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003686 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003687 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003688 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003689}
3690
3691// Test per-display input monitors for key event.
3692TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003693 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003694 FakeMonitorReceiver monitorInPrimary =
3695 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3696 FakeMonitorReceiver monitorInSecondary =
3697 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003698
3699 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003700 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3701 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003702 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003703 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003704 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003705 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003706}
3707
Vishnu Nair958da932020-08-21 17:12:37 -07003708TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3709 sp<FakeWindowHandle> secondWindowInPrimary =
3710 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3711 secondWindowInPrimary->setFocusable(true);
3712 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3713 setFocusedWindow(secondWindowInPrimary);
3714 windowInPrimary->consumeFocusEvent(false);
3715 secondWindowInPrimary->consumeFocusEvent(true);
3716
3717 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003718 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3719 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003720 windowInPrimary->assertNoEvents();
3721 windowInSecondary->assertNoEvents();
3722 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3723}
3724
Arthur Hungdfd528e2021-12-08 13:23:04 +00003725TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3726 FakeMonitorReceiver monitorInPrimary =
3727 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3728 FakeMonitorReceiver monitorInSecondary =
3729 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3730
3731 // Test touch down on primary display.
3732 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3733 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3734 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3735 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3736 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3737
3738 // Test touch down on second display.
3739 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3740 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3741 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3742 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3743 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3744
3745 // Trigger cancel touch.
3746 mDispatcher->cancelCurrentTouch();
3747 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3748 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3749 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3750 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3751
3752 // Test inject a move motion event, no window/monitor should receive the event.
3753 ASSERT_EQ(InputEventInjectionResult::FAILED,
3754 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3755 ADISPLAY_ID_DEFAULT, {110, 200}))
3756 << "Inject motion event should return InputEventInjectionResult::FAILED";
3757 windowInPrimary->assertNoEvents();
3758 monitorInPrimary.assertNoEvents();
3759
3760 ASSERT_EQ(InputEventInjectionResult::FAILED,
3761 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3762 SECOND_DISPLAY_ID, {110, 200}))
3763 << "Inject motion event should return InputEventInjectionResult::FAILED";
3764 windowInSecondary->assertNoEvents();
3765 monitorInSecondary.assertNoEvents();
3766}
3767
Jackal Guof9696682018-10-05 12:23:23 +08003768class InputFilterTest : public InputDispatcherTest {
3769protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003770 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3771 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003772 NotifyMotionArgs motionArgs;
3773
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003774 motionArgs =
3775 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003776 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003777 motionArgs =
3778 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003779 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003780 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003781 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003782 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3783 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003784 } else {
3785 mFakePolicy->assertFilterInputEventWasNotCalled();
3786 }
3787 }
3788
3789 void testNotifyKey(bool expectToBeFiltered) {
3790 NotifyKeyArgs keyArgs;
3791
3792 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3793 mDispatcher->notifyKey(&keyArgs);
3794 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3795 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003796 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003797
3798 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003799 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003800 } else {
3801 mFakePolicy->assertFilterInputEventWasNotCalled();
3802 }
3803 }
3804};
3805
3806// Test InputFilter for MotionEvent
3807TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3808 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3809 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3810 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3811
3812 // Enable InputFilter
3813 mDispatcher->setInputFilterEnabled(true);
3814 // Test touch on both primary and second display, and check if both events are filtered.
3815 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3816 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3817
3818 // Disable InputFilter
3819 mDispatcher->setInputFilterEnabled(false);
3820 // Test touch on both primary and second display, and check if both events aren't filtered.
3821 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3822 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3823}
3824
3825// Test InputFilter for KeyEvent
3826TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3827 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3828 testNotifyKey(/*expectToBeFiltered*/ false);
3829
3830 // Enable InputFilter
3831 mDispatcher->setInputFilterEnabled(true);
3832 // Send a key event, and check if it is filtered.
3833 testNotifyKey(/*expectToBeFiltered*/ true);
3834
3835 // Disable InputFilter
3836 mDispatcher->setInputFilterEnabled(false);
3837 // Send a key event, and check if it isn't filtered.
3838 testNotifyKey(/*expectToBeFiltered*/ false);
3839}
3840
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003841// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3842// logical display coordinate space.
3843TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3844 ui::Transform firstDisplayTransform;
3845 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3846 ui::Transform secondDisplayTransform;
3847 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3848
3849 std::vector<gui::DisplayInfo> displayInfos(2);
3850 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3851 displayInfos[0].transform = firstDisplayTransform;
3852 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3853 displayInfos[1].transform = secondDisplayTransform;
3854
3855 mDispatcher->onWindowInfosChanged({}, displayInfos);
3856
3857 // Enable InputFilter
3858 mDispatcher->setInputFilterEnabled(true);
3859
3860 // Ensure the correct transforms are used for the displays.
3861 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3862 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3863}
3864
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003865class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3866protected:
3867 virtual void SetUp() override {
3868 InputDispatcherTest::SetUp();
3869
3870 /**
3871 * We don't need to enable input filter to test the injected event policy, but we enabled it
3872 * here to make the tests more realistic, since this policy only matters when inputfilter is
3873 * on.
3874 */
3875 mDispatcher->setInputFilterEnabled(true);
3876
3877 std::shared_ptr<InputApplicationHandle> application =
3878 std::make_shared<FakeApplicationHandle>();
3879 mWindow =
3880 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3881
3882 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3883 mWindow->setFocusable(true);
3884 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3885 setFocusedWindow(mWindow);
3886 mWindow->consumeFocusEvent(true);
3887 }
3888
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003889 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3890 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003891 KeyEvent event;
3892
3893 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3894 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3895 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3896 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3897 const int32_t additionalPolicyFlags =
3898 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3899 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3900 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3901 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3902 policyFlags | additionalPolicyFlags));
3903
3904 InputEvent* received = mWindow->consume();
3905 ASSERT_NE(nullptr, received);
3906 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003907 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
3908 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
3909 ASSERT_EQ(flags, keyEvent.getFlags());
3910 }
3911
3912 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3913 int32_t flags) {
3914 MotionEvent event;
3915 PointerProperties pointerProperties[1];
3916 PointerCoords pointerCoords[1];
3917 pointerProperties[0].clear();
3918 pointerProperties[0].id = 0;
3919 pointerCoords[0].clear();
3920 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
3921 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
3922
3923 ui::Transform identityTransform;
3924 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3925 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
3926 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3927 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
3928 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07003929 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07003930 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003931 /*pointerCount*/ 1, pointerProperties, pointerCoords);
3932
3933 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
3934 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3935 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
3936 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3937 policyFlags | additionalPolicyFlags));
3938
3939 InputEvent* received = mWindow->consume();
3940 ASSERT_NE(nullptr, received);
3941 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
3942 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
3943 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
3944 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003945 }
3946
3947private:
3948 sp<FakeWindowHandle> mWindow;
3949};
3950
3951TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003952 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
3953 // filter. Without it, the event will no different from a regularly injected event, and the
3954 // injected device id will be overwritten.
3955 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3956 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003957}
3958
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003959TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003960 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003961 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3962 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
3963}
3964
3965TEST_F(InputFilterInjectionPolicyTest,
3966 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
3967 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
3968 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
3969 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003970}
3971
3972TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
3973 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003974 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003975}
3976
chaviwfd6d3512019-03-25 13:23:49 -07003977class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003978 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07003979 InputDispatcherTest::SetUp();
3980
Chris Yea209fde2020-07-22 13:54:51 -07003981 std::shared_ptr<FakeApplicationHandle> application =
3982 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003983 mUnfocusedWindow =
3984 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07003985 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
3986 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
3987 // window.
chaviw3277faf2021-05-19 16:45:23 -05003988 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003989
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003990 mFocusedWindow =
3991 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3992 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05003993 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
chaviwfd6d3512019-03-25 13:23:49 -07003994
3995 // Set focused application.
3996 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003997 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07003998
3999 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004000 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004001 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004002 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004003 }
4004
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004005 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004006 InputDispatcherTest::TearDown();
4007
4008 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004009 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004010 }
4011
4012protected:
4013 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004014 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004015 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004016};
4017
4018// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4019// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4020// the onPointerDownOutsideFocus callback.
4021TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004022 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004023 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4024 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004025 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004026 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004027
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004028 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004029 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4030}
4031
4032// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4033// DOWN on the window that doesn't have focus. Ensure no window received the
4034// onPointerDownOutsideFocus callback.
4035TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004036 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004037 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004038 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004039 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004040
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004041 ASSERT_TRUE(mDispatcher->waitForIdle());
4042 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004043}
4044
4045// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4046// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4047TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004048 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4049 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004050 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004051 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004052
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004053 ASSERT_TRUE(mDispatcher->waitForIdle());
4054 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004055}
4056
4057// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4058// DOWN on the window that already has focus. Ensure no window received the
4059// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004060TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004061 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004062 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004063 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004064 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004065 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004066
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004067 ASSERT_TRUE(mDispatcher->waitForIdle());
4068 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004069}
4070
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004071// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4072// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4073TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4074 const MotionEvent event =
4075 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4076 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4077 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4078 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4079 .build();
4080 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4081 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4082 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4083
4084 ASSERT_TRUE(mDispatcher->waitForIdle());
4085 mFakePolicy->assertOnPointerDownWasNotCalled();
4086 // Ensure that the unfocused window did not receive any FOCUS events.
4087 mUnfocusedWindow->assertNoEvents();
4088}
4089
chaviwaf87b3e2019-10-01 16:59:28 -07004090// These tests ensures we can send touch events to a single client when there are multiple input
4091// windows that point to the same client token.
4092class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4093 virtual void SetUp() override {
4094 InputDispatcherTest::SetUp();
4095
Chris Yea209fde2020-07-22 13:54:51 -07004096 std::shared_ptr<FakeApplicationHandle> application =
4097 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004098 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4099 ADISPLAY_ID_DEFAULT);
4100 // Adding FLAG_NOT_TOUCH_MODAL otherwise all taps will go to the top most window.
4101 // We also need FLAG_SPLIT_TOUCH or we won't be able to get touches for both windows.
chaviw3277faf2021-05-19 16:45:23 -05004102 mWindow1->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004103 mWindow1->setFrame(Rect(0, 0, 100, 100));
4104
4105 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4106 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviw3277faf2021-05-19 16:45:23 -05004107 mWindow2->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
chaviwaf87b3e2019-10-01 16:59:28 -07004108 mWindow2->setFrame(Rect(100, 100, 200, 200));
4109
Arthur Hung72d8dc32020-03-28 00:48:39 +00004110 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004111 }
4112
4113protected:
4114 sp<FakeWindowHandle> mWindow1;
4115 sp<FakeWindowHandle> mWindow2;
4116
4117 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004118 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004119 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4120 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004121 }
4122
4123 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4124 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004125 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004126 InputEvent* event = window->consume();
4127
4128 ASSERT_NE(nullptr, event) << name.c_str()
4129 << ": consumer should have returned non-NULL event.";
4130
4131 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4132 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4133 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4134
4135 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004136 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004137
4138 for (size_t i = 0; i < points.size(); i++) {
4139 float expectedX = points[i].x;
4140 float expectedY = points[i].y;
4141
4142 EXPECT_EQ(expectedX, motionEvent.getX(i))
4143 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4144 << ", got " << motionEvent.getX(i);
4145 EXPECT_EQ(expectedY, motionEvent.getY(i))
4146 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4147 << ", got " << motionEvent.getY(i);
4148 }
4149 }
chaviw9eaa22c2020-07-01 16:21:27 -07004150
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004151 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004152 std::vector<PointF> expectedPoints) {
4153 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4154 ADISPLAY_ID_DEFAULT, touchedPoints);
4155 mDispatcher->notifyMotion(&motionArgs);
4156
4157 // Always consume from window1 since it's the window that has the InputReceiver
4158 consumeMotionEvent(mWindow1, action, expectedPoints);
4159 }
chaviwaf87b3e2019-10-01 16:59:28 -07004160};
4161
4162TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4163 // Touch Window 1
4164 PointF touchedPoint = {10, 10};
4165 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004166 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004167
4168 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004169 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004170
4171 // Touch Window 2
4172 touchedPoint = {150, 150};
4173 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004174 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004175}
4176
chaviw9eaa22c2020-07-01 16:21:27 -07004177TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4178 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004179 mWindow2->setWindowScale(0.5f, 0.5f);
4180
4181 // Touch Window 1
4182 PointF touchedPoint = {10, 10};
4183 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004184 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004185 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004186 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004187
4188 // Touch Window 2
4189 touchedPoint = {150, 150};
4190 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004191 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4192 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004193
chaviw9eaa22c2020-07-01 16:21:27 -07004194 // Update the transform so rotation is set
4195 mWindow2->setWindowTransform(0, -1, 1, 0);
4196 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4197 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004198}
4199
chaviw9eaa22c2020-07-01 16:21:27 -07004200TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004201 mWindow2->setWindowScale(0.5f, 0.5f);
4202
4203 // Touch Window 1
4204 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4205 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004206 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004207
4208 // Touch Window 2
4209 int32_t actionPointerDown =
4210 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004211 touchedPoints.push_back(PointF{150, 150});
4212 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4213 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004214
chaviw9eaa22c2020-07-01 16:21:27 -07004215 // Release Window 2
4216 int32_t actionPointerUp =
4217 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4218 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4219 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004220
chaviw9eaa22c2020-07-01 16:21:27 -07004221 // Update the transform so rotation is set for Window 2
4222 mWindow2->setWindowTransform(0, -1, 1, 0);
4223 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4224 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004225}
4226
chaviw9eaa22c2020-07-01 16:21:27 -07004227TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004228 mWindow2->setWindowScale(0.5f, 0.5f);
4229
4230 // Touch Window 1
4231 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4232 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004233 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004234
4235 // Touch Window 2
4236 int32_t actionPointerDown =
4237 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004238 touchedPoints.push_back(PointF{150, 150});
4239 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004240
chaviw9eaa22c2020-07-01 16:21:27 -07004241 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004242
4243 // Move both windows
4244 touchedPoints = {{20, 20}, {175, 175}};
4245 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4246 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4247
chaviw9eaa22c2020-07-01 16:21:27 -07004248 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004249
chaviw9eaa22c2020-07-01 16:21:27 -07004250 // Release Window 2
4251 int32_t actionPointerUp =
4252 AMOTION_EVENT_ACTION_POINTER_UP + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
4253 touchAndAssertPositions(actionPointerUp, touchedPoints, expectedPoints);
4254 expectedPoints.pop_back();
4255
4256 // Touch Window 2
4257 mWindow2->setWindowTransform(0, -1, 1, 0);
4258 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
4259 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
4260
4261 // Move both windows
4262 touchedPoints = {{20, 20}, {175, 175}};
4263 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4264 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4265
4266 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004267}
4268
4269TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4270 mWindow1->setWindowScale(0.5f, 0.5f);
4271
4272 // Touch Window 1
4273 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4274 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004275 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004276
4277 // Touch Window 2
4278 int32_t actionPointerDown =
4279 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
chaviw9eaa22c2020-07-01 16:21:27 -07004280 touchedPoints.push_back(PointF{150, 150});
4281 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004282
chaviw9eaa22c2020-07-01 16:21:27 -07004283 touchAndAssertPositions(actionPointerDown, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004284
4285 // Move both windows
4286 touchedPoints = {{20, 20}, {175, 175}};
4287 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4288 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4289
chaviw9eaa22c2020-07-01 16:21:27 -07004290 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004291}
4292
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004293class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4294 virtual void SetUp() override {
4295 InputDispatcherTest::SetUp();
4296
Chris Yea209fde2020-07-22 13:54:51 -07004297 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004298 mApplication->setDispatchingTimeout(20ms);
4299 mWindow =
4300 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4301 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004302 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004303 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004304 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4305 // window.
chaviw3277faf2021-05-19 16:45:23 -05004306 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004307
4308 // Set focused application.
4309 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4310
4311 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004312 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004313 mWindow->consumeFocusEvent(true);
4314 }
4315
4316 virtual void TearDown() override {
4317 InputDispatcherTest::TearDown();
4318 mWindow.clear();
4319 }
4320
4321protected:
Chris Yea209fde2020-07-22 13:54:51 -07004322 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004323 sp<FakeWindowHandle> mWindow;
4324 static constexpr PointF WINDOW_LOCATION = {20, 20};
4325
4326 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004327 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004328 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4329 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004330 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004331 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4332 WINDOW_LOCATION));
4333 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004334
4335 sp<FakeWindowHandle> addSpyWindow() {
4336 sp<FakeWindowHandle> spy =
4337 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4338 spy->setTrustedOverlay(true);
4339 spy->setFocusable(false);
4340 spy->setInputFeatures(WindowInfo::Feature::SPY);
4341 spy->setDispatchingTimeout(30ms);
4342 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4343 return spy;
4344 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004345};
4346
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004347// Send a tap and respond, which should not cause an ANR.
4348TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4349 tapOnWindow();
4350 mWindow->consumeMotionDown();
4351 mWindow->consumeMotionUp();
4352 ASSERT_TRUE(mDispatcher->waitForIdle());
4353 mFakePolicy->assertNotifyAnrWasNotCalled();
4354}
4355
4356// Send a regular key and respond, which should not cause an ANR.
4357TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004358 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004359 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4360 ASSERT_TRUE(mDispatcher->waitForIdle());
4361 mFakePolicy->assertNotifyAnrWasNotCalled();
4362}
4363
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004364TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4365 mWindow->setFocusable(false);
4366 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4367 mWindow->consumeFocusEvent(false);
4368
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004369 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004370 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004371 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4372 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004373 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004374 // Key will not go to window because we have no focused window.
4375 // The 'no focused window' ANR timer should start instead.
4376
4377 // Now, the focused application goes away.
4378 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4379 // The key should get dropped and there should be no ANR.
4380
4381 ASSERT_TRUE(mDispatcher->waitForIdle());
4382 mFakePolicy->assertNotifyAnrWasNotCalled();
4383}
4384
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004385// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004386// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4387// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004388TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004389 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004390 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4391 WINDOW_LOCATION));
4392
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004393 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4394 ASSERT_TRUE(sequenceNum);
4395 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004396 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004397
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004398 mWindow->finishEvent(*sequenceNum);
4399 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4400 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004401 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004402 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004403}
4404
4405// Send a key to the app and have the app not respond right away.
4406TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4407 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004408 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004409 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4410 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004411 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004412 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004413 ASSERT_TRUE(mDispatcher->waitForIdle());
4414}
4415
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004416// We have a focused application, but no focused window
4417TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004418 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004419 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4420 mWindow->consumeFocusEvent(false);
4421
4422 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004423 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004424 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4425 WINDOW_LOCATION));
4426 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4427 mDispatcher->waitForIdle();
4428 mFakePolicy->assertNotifyAnrWasNotCalled();
4429
4430 // Once a focused event arrives, we get an ANR for this application
4431 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4432 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004433 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004434 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004435 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004436 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004437 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004438 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004439 ASSERT_TRUE(mDispatcher->waitForIdle());
4440}
4441
4442// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004443// Make sure that we don't notify policy twice about the same ANR.
4444TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004445 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004446 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4447 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004448
4449 // Once a focused event arrives, we get an ANR for this application
4450 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4451 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004452 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004453 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004454 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004455 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004456 const std::chrono::duration appTimeout =
4457 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004458 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004459
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004460 std::this_thread::sleep_for(appTimeout);
4461 // ANR should not be raised again. It is up to policy to do that if it desires.
4462 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004463
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004464 // If we now get a focused window, the ANR should stop, but the policy handles that via
4465 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004466 ASSERT_TRUE(mDispatcher->waitForIdle());
4467}
4468
4469// We have a focused application, but no focused window
4470TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004471 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004472 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4473 mWindow->consumeFocusEvent(false);
4474
4475 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004476 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004477 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004478 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4479 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004480
4481 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004482 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004483
4484 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004485 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004486 ASSERT_TRUE(mDispatcher->waitForIdle());
4487 mWindow->assertNoEvents();
4488}
4489
4490/**
4491 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4492 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4493 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4494 * the ANR mechanism should still work.
4495 *
4496 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4497 * DOWN event, while not responding on the second one.
4498 */
4499TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4500 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4501 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4502 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4503 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4504 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004505 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004506
4507 // Now send ACTION_UP, with identical timestamp
4508 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4509 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4510 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4511 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004512 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004513
4514 // We have now sent down and up. Let's consume first event and then ANR on the second.
4515 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4516 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004517 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004518}
4519
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004520// A spy window can receive an ANR
4521TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4522 sp<FakeWindowHandle> spy = addSpyWindow();
4523
4524 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4525 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4526 WINDOW_LOCATION));
4527 mWindow->consumeMotionDown();
4528
4529 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4530 ASSERT_TRUE(sequenceNum);
4531 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
4532 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy->getToken());
4533
4534 spy->finishEvent(*sequenceNum);
4535 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4536 0 /*flags*/);
4537 ASSERT_TRUE(mDispatcher->waitForIdle());
4538 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken());
4539}
4540
4541// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004542// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004543TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4544 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004545
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004546 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4547 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004548 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004549 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004550
4551 // Stuck on the ACTION_UP
4552 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004553 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004554
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004555 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004556 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004557 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4558 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004559
4560 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4561 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004562 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004563 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004564 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004565}
4566
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004567// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004568// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004569TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4570 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004571
4572 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004573 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4574 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004575
4576 mWindow->consumeMotionDown();
4577 // Stuck on the ACTION_UP
4578 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004579 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004580
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004581 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004582 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004583 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4584 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004585
4586 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4587 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004588 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004589 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004590 spy->assertNoEvents();
4591}
4592
4593TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4594 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4595
4596 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4597
4598 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4599 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4600 WINDOW_LOCATION));
4601
4602 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4603 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4604 ASSERT_TRUE(consumeSeq);
4605
4606 mFakePolicy->assertNotifyMonitorUnresponsiveWasCalled(30ms);
4607
4608 monitor.finishEvent(*consumeSeq);
4609 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4610
4611 ASSERT_TRUE(mDispatcher->waitForIdle());
4612 mFakePolicy->assertNotifyMonitorResponsiveWasCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004613}
4614
4615// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4616// process events, you don't get an anr. When the window later becomes unresponsive again, you
4617// get an ANR again.
4618// 1. tap -> block on ACTION_UP -> receive ANR
4619// 2. consume all pending events (= queue becomes healthy again)
4620// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4621TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4622 tapOnWindow();
4623
4624 mWindow->consumeMotionDown();
4625 // Block on ACTION_UP
4626 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004627 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004628 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4629 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004630 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004631 mWindow->assertNoEvents();
4632
4633 tapOnWindow();
4634 mWindow->consumeMotionDown();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004635 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004636 mWindow->consumeMotionUp();
4637
4638 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004639 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004640 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004641 mWindow->assertNoEvents();
4642}
4643
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004644// If a connection remains unresponsive for a while, make sure policy is only notified once about
4645// it.
4646TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004647 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004648 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4649 WINDOW_LOCATION));
4650
4651 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004652 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004653 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004654 // 'notifyConnectionUnresponsive' should only be called once per connection
4655 mFakePolicy->assertNotifyAnrWasNotCalled();
4656 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004657 mWindow->consumeMotionDown();
4658 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4659 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4660 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004661 mDispatcher->waitForIdle();
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004662 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004663 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004664}
4665
4666/**
4667 * If a window is processing a motion event, and then a key event comes in, the key event should
4668 * not to to the focused window until the motion is processed.
4669 *
4670 * Warning!!!
4671 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4672 * and the injection timeout that we specify when injecting the key.
4673 * We must have the injection timeout (10ms) be smaller than
4674 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4675 *
4676 * If that value changes, this test should also change.
4677 */
4678TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4679 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4680 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4681
4682 tapOnWindow();
4683 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4684 ASSERT_TRUE(downSequenceNum);
4685 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4686 ASSERT_TRUE(upSequenceNum);
4687 // Don't finish the events yet, and send a key
4688 // Injection will "succeed" because we will eventually give up and send the key to the focused
4689 // window even if motions are still being processed. But because the injection timeout is short,
4690 // we will receive INJECTION_TIMED_OUT as the result.
4691
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004692 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004693 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004694 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4695 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004696 // Key will not be sent to the window, yet, because the window is still processing events
4697 // and the key remains pending, waiting for the touch events to be processed
4698 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4699 ASSERT_FALSE(keySequenceNum);
4700
4701 std::this_thread::sleep_for(500ms);
4702 // if we wait long enough though, dispatcher will give up, and still send the key
4703 // to the focused window, even though we have not yet finished the motion event
4704 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4705 mWindow->finishEvent(*downSequenceNum);
4706 mWindow->finishEvent(*upSequenceNum);
4707}
4708
4709/**
4710 * If a window is processing a motion event, and then a key event comes in, the key event should
4711 * not go to the focused window until the motion is processed.
4712 * If then a new motion comes in, then the pending key event should be going to the currently
4713 * focused window right away.
4714 */
4715TEST_F(InputDispatcherSingleWindowAnr,
4716 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4717 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4718 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4719
4720 tapOnWindow();
4721 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4722 ASSERT_TRUE(downSequenceNum);
4723 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4724 ASSERT_TRUE(upSequenceNum);
4725 // Don't finish the events yet, and send a key
4726 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004727 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004728 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004729 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004730 // At this point, key is still pending, and should not be sent to the application yet.
4731 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4732 ASSERT_FALSE(keySequenceNum);
4733
4734 // Now tap down again. It should cause the pending key to go to the focused window right away.
4735 tapOnWindow();
4736 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4737 // the other events yet. We can finish events in any order.
4738 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4739 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4740 mWindow->consumeMotionDown();
4741 mWindow->consumeMotionUp();
4742 mWindow->assertNoEvents();
4743}
4744
4745class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4746 virtual void SetUp() override {
4747 InputDispatcherTest::SetUp();
4748
Chris Yea209fde2020-07-22 13:54:51 -07004749 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004750 mApplication->setDispatchingTimeout(10ms);
4751 mUnfocusedWindow =
4752 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4753 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
4754 // Adding FLAG_NOT_TOUCH_MODAL to ensure taps outside this window are not sent to this
4755 // window.
4756 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
chaviw3277faf2021-05-19 16:45:23 -05004757 mUnfocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL |
4758 WindowInfo::Flag::WATCH_OUTSIDE_TOUCH |
4759 WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004760
4761 mFocusedWindow =
4762 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004763 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004764 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05004765 mFocusedWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004766
4767 // Set focused application.
4768 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004769 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004770
4771 // Expect one focus window exist in display.
4772 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004773 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004774 mFocusedWindow->consumeFocusEvent(true);
4775 }
4776
4777 virtual void TearDown() override {
4778 InputDispatcherTest::TearDown();
4779
4780 mUnfocusedWindow.clear();
4781 mFocusedWindow.clear();
4782 }
4783
4784protected:
Chris Yea209fde2020-07-22 13:54:51 -07004785 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004786 sp<FakeWindowHandle> mUnfocusedWindow;
4787 sp<FakeWindowHandle> mFocusedWindow;
4788 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4789 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4790 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4791
4792 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4793
4794 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4795
4796private:
4797 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004798 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004799 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4800 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004801 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004802 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4803 location));
4804 }
4805};
4806
4807// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4808// should be ANR'd first.
4809TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004810 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004811 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4812 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004813 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004814 mFocusedWindow->consumeMotionDown();
4815 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4816 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4817 // We consumed all events, so no ANR
4818 ASSERT_TRUE(mDispatcher->waitForIdle());
4819 mFakePolicy->assertNotifyAnrWasNotCalled();
4820
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004821 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004822 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4823 FOCUSED_WINDOW_LOCATION));
4824 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4825 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004826
4827 const std::chrono::duration timeout =
4828 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004829 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004830 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4831 // sequence to make it consistent
4832 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004833 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004834 mFocusedWindow->consumeMotionDown();
4835 // This cancel is generated because the connection was unresponsive
4836 mFocusedWindow->consumeMotionCancel();
4837 mFocusedWindow->assertNoEvents();
4838 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004839 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004840 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004841 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004842}
4843
4844// If we have 2 windows with identical timeouts that are both unresponsive,
4845// it doesn't matter which order they should have ANR.
4846// But we should receive ANR for both.
4847TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4848 // Set the timeout for unfocused window to match the focused window
4849 mUnfocusedWindow->setDispatchingTimeout(10ms);
4850 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4851
4852 tapOnFocusedWindow();
4853 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004854 sp<IBinder> anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms);
4855 sp<IBinder> anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004856
4857 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004858 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4859 mFocusedWindow->getToken() == anrConnectionToken2);
4860 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4861 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004862
4863 ASSERT_TRUE(mDispatcher->waitForIdle());
4864 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004865
4866 mFocusedWindow->consumeMotionDown();
4867 mFocusedWindow->consumeMotionUp();
4868 mUnfocusedWindow->consumeMotionOutside();
4869
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004870 sp<IBinder> responsiveToken1 = mFakePolicy->getResponsiveWindowToken();
4871 sp<IBinder> responsiveToken2 = mFakePolicy->getResponsiveWindowToken();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004872
4873 // Both applications should be marked as responsive, in any order
4874 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4875 mFocusedWindow->getToken() == responsiveToken2);
4876 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4877 mUnfocusedWindow->getToken() == responsiveToken2);
4878 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004879}
4880
4881// If a window is already not responding, the second tap on the same window should be ignored.
4882// We should also log an error to account for the dropped event (not tested here).
4883// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4884TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4885 tapOnFocusedWindow();
4886 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4887 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4888 // Receive the events, but don't respond
4889 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4890 ASSERT_TRUE(downEventSequenceNum);
4891 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4892 ASSERT_TRUE(upEventSequenceNum);
4893 const std::chrono::duration timeout =
4894 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004895 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004896
4897 // Tap once again
4898 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004899 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004900 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4901 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004902 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004903 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4904 FOCUSED_WINDOW_LOCATION));
4905 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
4906 // valid touch target
4907 mUnfocusedWindow->assertNoEvents();
4908
4909 // Consume the first tap
4910 mFocusedWindow->finishEvent(*downEventSequenceNum);
4911 mFocusedWindow->finishEvent(*upEventSequenceNum);
4912 ASSERT_TRUE(mDispatcher->waitForIdle());
4913 // The second tap did not go to the focused window
4914 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004915 // Since all events are finished, connection should be deemed healthy again
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00004916 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004917 mFakePolicy->assertNotifyAnrWasNotCalled();
4918}
4919
4920// If you tap outside of all windows, there will not be ANR
4921TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004922 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004923 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4924 LOCATION_OUTSIDE_ALL_WINDOWS));
4925 ASSERT_TRUE(mDispatcher->waitForIdle());
4926 mFakePolicy->assertNotifyAnrWasNotCalled();
4927}
4928
4929// Since the focused window is paused, tapping on it should not produce any events
4930TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
4931 mFocusedWindow->setPaused(true);
4932 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4933
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004934 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004935 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4936 FOCUSED_WINDOW_LOCATION));
4937
4938 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
4939 ASSERT_TRUE(mDispatcher->waitForIdle());
4940 // Should not ANR because the window is paused, and touches shouldn't go to it
4941 mFakePolicy->assertNotifyAnrWasNotCalled();
4942
4943 mFocusedWindow->assertNoEvents();
4944 mUnfocusedWindow->assertNoEvents();
4945}
4946
4947/**
4948 * If a window is processing a motion event, and then a key event comes in, the key event should
4949 * not to to the focused window until the motion is processed.
4950 * If a different window becomes focused at this time, the key should go to that window instead.
4951 *
4952 * Warning!!!
4953 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4954 * and the injection timeout that we specify when injecting the key.
4955 * We must have the injection timeout (10ms) be smaller than
4956 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4957 *
4958 * If that value changes, this test should also change.
4959 */
4960TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
4961 // Set a long ANR timeout to prevent it from triggering
4962 mFocusedWindow->setDispatchingTimeout(2s);
4963 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
4964
4965 tapOnUnfocusedWindow();
4966 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
4967 ASSERT_TRUE(downSequenceNum);
4968 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
4969 ASSERT_TRUE(upSequenceNum);
4970 // Don't finish the events yet, and send a key
4971 // Injection will succeed because we will eventually give up and send the key to the focused
4972 // window even if motions are still being processed.
4973
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004974 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004975 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004976 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
4977 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004978 // Key will not be sent to the window, yet, because the window is still processing events
4979 // and the key remains pending, waiting for the touch events to be processed
4980 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
4981 ASSERT_FALSE(keySequenceNum);
4982
4983 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07004984 mFocusedWindow->setFocusable(false);
4985 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004986 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004987 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004988
4989 // Focus events should precede the key events
4990 mUnfocusedWindow->consumeFocusEvent(true);
4991 mFocusedWindow->consumeFocusEvent(false);
4992
4993 // Finish the tap events, which should unblock dispatcher
4994 mUnfocusedWindow->finishEvent(*downSequenceNum);
4995 mUnfocusedWindow->finishEvent(*upSequenceNum);
4996
4997 // Now that all queues are cleared and no backlog in the connections, the key event
4998 // can finally go to the newly focused "mUnfocusedWindow".
4999 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5000 mFocusedWindow->assertNoEvents();
5001 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005002 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005003}
5004
5005// When the touch stream is split across 2 windows, and one of them does not respond,
5006// then ANR should be raised and the touch should be canceled for the unresponsive window.
5007// The other window should not be affected by that.
5008TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5009 // Touch Window 1
5010 NotifyMotionArgs motionArgs =
5011 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5012 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5013 mDispatcher->notifyMotion(&motionArgs);
5014 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5015 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5016
5017 // Touch Window 2
5018 int32_t actionPointerDown =
5019 AMOTION_EVENT_ACTION_POINTER_DOWN + (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
5020
5021 motionArgs =
5022 generateMotionArgs(actionPointerDown, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5023 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
5024 mDispatcher->notifyMotion(&motionArgs);
5025
5026 const std::chrono::duration timeout =
5027 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005028 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow->getToken());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005029
5030 mUnfocusedWindow->consumeMotionDown();
5031 mFocusedWindow->consumeMotionDown();
5032 // Focused window may or may not receive ACTION_MOVE
5033 // But it should definitely receive ACTION_CANCEL due to the ANR
5034 InputEvent* event;
5035 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5036 ASSERT_TRUE(moveOrCancelSequenceNum);
5037 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5038 ASSERT_NE(nullptr, event);
5039 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5040 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5041 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5042 mFocusedWindow->consumeMotionCancel();
5043 } else {
5044 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5045 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005046 ASSERT_TRUE(mDispatcher->waitForIdle());
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +00005047 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005048
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005049 mUnfocusedWindow->assertNoEvents();
5050 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005051 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005052}
5053
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005054/**
5055 * If we have no focused window, and a key comes in, we start the ANR timer.
5056 * The focused application should add a focused window before the timer runs out to prevent ANR.
5057 *
5058 * If the user touches another application during this time, the key should be dropped.
5059 * Next, if a new focused window comes in, without toggling the focused application,
5060 * then no ANR should occur.
5061 *
5062 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5063 * but in some cases the policy may not update the focused application.
5064 */
5065TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5066 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5067 std::make_shared<FakeApplicationHandle>();
5068 focusedApplication->setDispatchingTimeout(60ms);
5069 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5070 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5071 mFocusedWindow->setFocusable(false);
5072
5073 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5074 mFocusedWindow->consumeFocusEvent(false);
5075
5076 // Send a key. The ANR timer should start because there is no focused window.
5077 // 'focusedApplication' will get blamed if this timer completes.
5078 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005079 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005080 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005081 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5082 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005083 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005084
5085 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5086 // then the injected touches won't cause the focused event to get dropped.
5087 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5088 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5089 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5090 // For this test, it means that the key would get delivered to the window once it becomes
5091 // focused.
5092 std::this_thread::sleep_for(10ms);
5093
5094 // Touch unfocused window. This should force the pending key to get dropped.
5095 NotifyMotionArgs motionArgs =
5096 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5097 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5098 mDispatcher->notifyMotion(&motionArgs);
5099
5100 // We do not consume the motion right away, because that would require dispatcher to first
5101 // process (== drop) the key event, and by that time, ANR will be raised.
5102 // Set the focused window first.
5103 mFocusedWindow->setFocusable(true);
5104 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5105 setFocusedWindow(mFocusedWindow);
5106 mFocusedWindow->consumeFocusEvent(true);
5107 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5108 // to another application. This could be a bug / behaviour in the policy.
5109
5110 mUnfocusedWindow->consumeMotionDown();
5111
5112 ASSERT_TRUE(mDispatcher->waitForIdle());
5113 // Should not ANR because we actually have a focused window. It was just added too slowly.
5114 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5115}
5116
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005117// These tests ensure we cannot send touch events to a window that's positioned behind a window
5118// that has feature NO_INPUT_CHANNEL.
5119// Layout:
5120// Top (closest to user)
5121// mNoInputWindow (above all windows)
5122// mBottomWindow
5123// Bottom (furthest from user)
5124class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5125 virtual void SetUp() override {
5126 InputDispatcherTest::SetUp();
5127
5128 mApplication = std::make_shared<FakeApplicationHandle>();
5129 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5130 "Window without input channel", ADISPLAY_ID_DEFAULT,
5131 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5132
chaviw3277faf2021-05-19 16:45:23 -05005133 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005134 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5135 // It's perfectly valid for this window to not have an associated input channel
5136
5137 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5138 ADISPLAY_ID_DEFAULT);
5139 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5140
5141 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5142 }
5143
5144protected:
5145 std::shared_ptr<FakeApplicationHandle> mApplication;
5146 sp<FakeWindowHandle> mNoInputWindow;
5147 sp<FakeWindowHandle> mBottomWindow;
5148};
5149
5150TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5151 PointF touchedPoint = {10, 10};
5152
5153 NotifyMotionArgs motionArgs =
5154 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5155 ADISPLAY_ID_DEFAULT, {touchedPoint});
5156 mDispatcher->notifyMotion(&motionArgs);
5157
5158 mNoInputWindow->assertNoEvents();
5159 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5160 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5161 // and therefore should prevent mBottomWindow from receiving touches
5162 mBottomWindow->assertNoEvents();
5163}
5164
5165/**
5166 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5167 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5168 */
5169TEST_F(InputDispatcherMultiWindowOcclusionTests,
5170 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5171 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5172 "Window with input channel and NO_INPUT_CHANNEL",
5173 ADISPLAY_ID_DEFAULT);
5174
chaviw3277faf2021-05-19 16:45:23 -05005175 mNoInputWindow->setInputFeatures(WindowInfo::Feature::NO_INPUT_CHANNEL);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005176 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5177 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5178
5179 PointF touchedPoint = {10, 10};
5180
5181 NotifyMotionArgs motionArgs =
5182 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5183 ADISPLAY_ID_DEFAULT, {touchedPoint});
5184 mDispatcher->notifyMotion(&motionArgs);
5185
5186 mNoInputWindow->assertNoEvents();
5187 mBottomWindow->assertNoEvents();
5188}
5189
Vishnu Nair958da932020-08-21 17:12:37 -07005190class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5191protected:
5192 std::shared_ptr<FakeApplicationHandle> mApp;
5193 sp<FakeWindowHandle> mWindow;
5194 sp<FakeWindowHandle> mMirror;
5195
5196 virtual void SetUp() override {
5197 InputDispatcherTest::SetUp();
5198 mApp = std::make_shared<FakeApplicationHandle>();
5199 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5200 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5201 mWindow->getToken());
5202 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5203 mWindow->setFocusable(true);
5204 mMirror->setFocusable(true);
5205 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5206 }
5207};
5208
5209TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5210 // Request focus on a mirrored window
5211 setFocusedWindow(mMirror);
5212
5213 // window gets focused
5214 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005215 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5216 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005217 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5218}
5219
5220// A focused & mirrored window remains focused only if the window and its mirror are both
5221// focusable.
5222TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5223 setFocusedWindow(mMirror);
5224
5225 // window gets focused
5226 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005227 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5228 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005229 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005230 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5231 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005232 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5233
5234 mMirror->setFocusable(false);
5235 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5236
5237 // window loses focus since one of the windows associated with the token in not focusable
5238 mWindow->consumeFocusEvent(false);
5239
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005240 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5241 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005242 mWindow->assertNoEvents();
5243}
5244
5245// A focused & mirrored window remains focused until the window and its mirror both become
5246// invisible.
5247TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5248 setFocusedWindow(mMirror);
5249
5250 // window gets focused
5251 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005252 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5253 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005254 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005255 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5256 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005257 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5258
5259 mMirror->setVisible(false);
5260 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5261
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005262 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5263 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005264 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005265 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5266 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005267 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5268
5269 mWindow->setVisible(false);
5270 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5271
5272 // window loses focus only after all windows associated with the token become invisible.
5273 mWindow->consumeFocusEvent(false);
5274
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005275 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5276 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005277 mWindow->assertNoEvents();
5278}
5279
5280// A focused & mirrored window remains focused until both windows are removed.
5281TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5282 setFocusedWindow(mMirror);
5283
5284 // window gets focused
5285 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005286 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5287 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005288 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005289 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5290 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005291 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5292
5293 // single window is removed but the window token remains focused
5294 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5295
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005296 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5297 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005298 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005299 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5300 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005301 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5302
5303 // Both windows are removed
5304 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5305 mWindow->consumeFocusEvent(false);
5306
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005307 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5308 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005309 mWindow->assertNoEvents();
5310}
5311
5312// Focus request can be pending until one window becomes visible.
5313TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5314 // Request focus on an invisible mirror.
5315 mWindow->setVisible(false);
5316 mMirror->setVisible(false);
5317 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5318 setFocusedWindow(mMirror);
5319
5320 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005321 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005322 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005323 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005324
5325 mMirror->setVisible(true);
5326 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5327
5328 // window gets focused
5329 mWindow->consumeFocusEvent(true);
5330 // window gets the pending key event
5331 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5332}
Prabir Pradhan99987712020-11-10 18:43:05 -08005333
5334class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5335protected:
5336 std::shared_ptr<FakeApplicationHandle> mApp;
5337 sp<FakeWindowHandle> mWindow;
5338 sp<FakeWindowHandle> mSecondWindow;
5339
5340 void SetUp() override {
5341 InputDispatcherTest::SetUp();
5342 mApp = std::make_shared<FakeApplicationHandle>();
5343 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5344 mWindow->setFocusable(true);
5345 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5346 mSecondWindow->setFocusable(true);
5347
5348 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5349 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5350
5351 setFocusedWindow(mWindow);
5352 mWindow->consumeFocusEvent(true);
5353 }
5354
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005355 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5356 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005357 mDispatcher->notifyPointerCaptureChanged(&args);
5358 }
5359
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005360 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5361 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005362 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005363 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5364 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005365 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005366 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005367 }
5368};
5369
5370TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5371 // Ensure that capture cannot be obtained for unfocused windows.
5372 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5373 mFakePolicy->assertSetPointerCaptureNotCalled();
5374 mSecondWindow->assertNoEvents();
5375
5376 // Ensure that capture can be enabled from the focus window.
5377 requestAndVerifyPointerCapture(mWindow, true);
5378
5379 // Ensure that capture cannot be disabled from a window that does not have capture.
5380 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5381 mFakePolicy->assertSetPointerCaptureNotCalled();
5382
5383 // Ensure that capture can be disabled from the window with capture.
5384 requestAndVerifyPointerCapture(mWindow, false);
5385}
5386
5387TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005388 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005389
5390 setFocusedWindow(mSecondWindow);
5391
5392 // Ensure that the capture disabled event was sent first.
5393 mWindow->consumeCaptureEvent(false);
5394 mWindow->consumeFocusEvent(false);
5395 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005396 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005397
5398 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005399 notifyPointerCaptureChanged({});
5400 notifyPointerCaptureChanged(request);
5401 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005402 mWindow->assertNoEvents();
5403 mSecondWindow->assertNoEvents();
5404 mFakePolicy->assertSetPointerCaptureNotCalled();
5405}
5406
5407TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005408 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005409
5410 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005411 notifyPointerCaptureChanged({});
5412 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005413
5414 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005415 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005416 mWindow->consumeCaptureEvent(false);
5417 mWindow->assertNoEvents();
5418}
5419
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005420TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5421 requestAndVerifyPointerCapture(mWindow, true);
5422
5423 // The first window loses focus.
5424 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005425 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005426 mWindow->consumeCaptureEvent(false);
5427
5428 // Request Pointer Capture from the second window before the notification from InputReader
5429 // arrives.
5430 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005431 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005432
5433 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005434 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005435
5436 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005437 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005438
5439 mSecondWindow->consumeFocusEvent(true);
5440 mSecondWindow->consumeCaptureEvent(true);
5441}
5442
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005443TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5444 // App repeatedly enables and disables capture.
5445 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5446 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5447 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5448 mFakePolicy->assertSetPointerCaptureCalled(false);
5449 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5450 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5451
5452 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5453 // first request is now stale, this should do nothing.
5454 notifyPointerCaptureChanged(firstRequest);
5455 mWindow->assertNoEvents();
5456
5457 // InputReader notifies that the second request was enabled.
5458 notifyPointerCaptureChanged(secondRequest);
5459 mWindow->consumeCaptureEvent(true);
5460}
5461
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005462class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5463protected:
5464 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005465
5466 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5467 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5468
5469 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5470 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5471
5472 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5473 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5474 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5475 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5476 MAXIMUM_OBSCURING_OPACITY);
5477
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005478 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005479 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005480 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005481
5482 sp<FakeWindowHandle> mTouchWindow;
5483
5484 virtual void SetUp() override {
5485 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005486 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005487 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5488 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5489 }
5490
5491 virtual void TearDown() override {
5492 InputDispatcherTest::TearDown();
5493 mTouchWindow.clear();
5494 }
5495
chaviw3277faf2021-05-19 16:45:23 -05005496 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5497 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005498 sp<FakeWindowHandle> window = getWindow(uid, name);
chaviw3277faf2021-05-19 16:45:23 -05005499 window->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005500 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005501 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005502 return window;
5503 }
5504
5505 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5506 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5507 sp<FakeWindowHandle> window =
5508 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5509 // Generate an arbitrary PID based on the UID
5510 window->setOwnerInfo(1777 + (uid % 10000), uid);
5511 return window;
5512 }
5513
5514 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5515 NotifyMotionArgs args =
5516 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5517 ADISPLAY_ID_DEFAULT, points);
5518 mDispatcher->notifyMotion(&args);
5519 }
5520};
5521
5522TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005523 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005524 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005525 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005526
5527 touch();
5528
5529 mTouchWindow->assertNoEvents();
5530}
5531
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005532TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005533 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5534 const sp<FakeWindowHandle>& w =
5535 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5536 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5537
5538 touch();
5539
5540 mTouchWindow->assertNoEvents();
5541}
5542
5543TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005544 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5545 const sp<FakeWindowHandle>& w =
5546 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5547 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5548
5549 touch();
5550
5551 w->assertNoEvents();
5552}
5553
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005554TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005555 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5556 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005557
5558 touch();
5559
5560 mTouchWindow->consumeAnyMotionDown();
5561}
5562
5563TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005564 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005565 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005566 w->setFrame(Rect(0, 0, 50, 50));
5567 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005568
5569 touch({PointF{100, 100}});
5570
5571 mTouchWindow->consumeAnyMotionDown();
5572}
5573
5574TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005575 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005576 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005577 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5578
5579 touch();
5580
5581 mTouchWindow->consumeAnyMotionDown();
5582}
5583
5584TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5585 const sp<FakeWindowHandle>& w =
5586 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5587 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005588
5589 touch();
5590
5591 mTouchWindow->consumeAnyMotionDown();
5592}
5593
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005594TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5595 const sp<FakeWindowHandle>& w =
5596 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5597 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5598
5599 touch();
5600
5601 w->assertNoEvents();
5602}
5603
5604/**
5605 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5606 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5607 * window, the occluding window will still receive ACTION_OUTSIDE event.
5608 */
5609TEST_F(InputDispatcherUntrustedTouchesTest,
5610 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5611 const sp<FakeWindowHandle>& w =
5612 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005613 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005614 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5615
5616 touch();
5617
5618 w->consumeMotionOutside();
5619}
5620
5621TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5622 const sp<FakeWindowHandle>& w =
5623 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
chaviw3277faf2021-05-19 16:45:23 -05005624 w->addFlags(WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005625 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5626
5627 touch();
5628
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005629 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005630}
5631
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005632TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005633 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005634 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5635 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005636 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5637
5638 touch();
5639
5640 mTouchWindow->consumeAnyMotionDown();
5641}
5642
5643TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5644 const sp<FakeWindowHandle>& w =
5645 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5646 MAXIMUM_OBSCURING_OPACITY);
5647 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005648
5649 touch();
5650
5651 mTouchWindow->consumeAnyMotionDown();
5652}
5653
5654TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005655 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005656 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5657 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005658 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5659
5660 touch();
5661
5662 mTouchWindow->assertNoEvents();
5663}
5664
5665TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5666 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5667 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005668 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5669 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005670 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005671 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5672 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005673 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5674
5675 touch();
5676
5677 mTouchWindow->assertNoEvents();
5678}
5679
5680TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5681 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5682 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005683 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5684 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005685 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005686 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5687 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005688 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5689
5690 touch();
5691
5692 mTouchWindow->consumeAnyMotionDown();
5693}
5694
5695TEST_F(InputDispatcherUntrustedTouchesTest,
5696 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5697 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005698 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5699 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005700 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005701 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5702 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005703 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5704
5705 touch();
5706
5707 mTouchWindow->consumeAnyMotionDown();
5708}
5709
5710TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5711 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005712 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5713 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005714 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005715 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5716 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005717 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005718
5719 touch();
5720
5721 mTouchWindow->assertNoEvents();
5722}
5723
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005724TEST_F(InputDispatcherUntrustedTouchesTest,
5725 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5726 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005727 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5728 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005729 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005730 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5731 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005732 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5733
5734 touch();
5735
5736 mTouchWindow->assertNoEvents();
5737}
5738
5739TEST_F(InputDispatcherUntrustedTouchesTest,
5740 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5741 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005742 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5743 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005744 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005745 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5746 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005747 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5748
5749 touch();
5750
5751 mTouchWindow->consumeAnyMotionDown();
5752}
5753
5754TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5755 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005756 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5757 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005758 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5759
5760 touch();
5761
5762 mTouchWindow->consumeAnyMotionDown();
5763}
5764
5765TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5766 const sp<FakeWindowHandle>& w =
5767 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5768 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5769
5770 touch();
5771
5772 mTouchWindow->consumeAnyMotionDown();
5773}
5774
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005775TEST_F(InputDispatcherUntrustedTouchesTest,
5776 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5777 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5778 const sp<FakeWindowHandle>& w =
5779 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5780 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5781
5782 touch();
5783
5784 mTouchWindow->assertNoEvents();
5785}
5786
5787TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5788 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5789 const sp<FakeWindowHandle>& w =
5790 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5791 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5792
5793 touch();
5794
5795 mTouchWindow->consumeAnyMotionDown();
5796}
5797
5798TEST_F(InputDispatcherUntrustedTouchesTest,
5799 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5800 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5801 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005802 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5803 OPACITY_ABOVE_THRESHOLD);
5804 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5805
5806 touch();
5807
5808 mTouchWindow->consumeAnyMotionDown();
5809}
5810
5811TEST_F(InputDispatcherUntrustedTouchesTest,
5812 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5813 const sp<FakeWindowHandle>& w1 =
5814 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5815 OPACITY_BELOW_THRESHOLD);
5816 const sp<FakeWindowHandle>& w2 =
5817 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5818 OPACITY_BELOW_THRESHOLD);
5819 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5820
5821 touch();
5822
5823 mTouchWindow->assertNoEvents();
5824}
5825
5826/**
5827 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5828 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5829 * (which alone would result in allowing touches) does not affect the blocking behavior.
5830 */
5831TEST_F(InputDispatcherUntrustedTouchesTest,
5832 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5833 const sp<FakeWindowHandle>& wB =
5834 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5835 OPACITY_BELOW_THRESHOLD);
5836 const sp<FakeWindowHandle>& wC =
5837 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5838 OPACITY_BELOW_THRESHOLD);
5839 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5840
5841 touch();
5842
5843 mTouchWindow->assertNoEvents();
5844}
5845
5846/**
5847 * This test is testing that a window from a different UID but with same application token doesn't
5848 * block the touch. Apps can share the application token for close UI collaboration for example.
5849 */
5850TEST_F(InputDispatcherUntrustedTouchesTest,
5851 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5852 const sp<FakeWindowHandle>& w =
5853 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5854 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005855 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5856
5857 touch();
5858
5859 mTouchWindow->consumeAnyMotionDown();
5860}
5861
arthurhungb89ccb02020-12-30 16:19:01 +08005862class InputDispatcherDragTests : public InputDispatcherTest {
5863protected:
5864 std::shared_ptr<FakeApplicationHandle> mApp;
5865 sp<FakeWindowHandle> mWindow;
5866 sp<FakeWindowHandle> mSecondWindow;
5867 sp<FakeWindowHandle> mDragWindow;
5868
5869 void SetUp() override {
5870 InputDispatcherTest::SetUp();
5871 mApp = std::make_shared<FakeApplicationHandle>();
5872 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5873 mWindow->setFrame(Rect(0, 0, 100, 100));
chaviw3277faf2021-05-19 16:45:23 -05005874 mWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005875
5876 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5877 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
chaviw3277faf2021-05-19 16:45:23 -05005878 mSecondWindow->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL);
arthurhungb89ccb02020-12-30 16:19:01 +08005879
5880 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5881 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5882 }
5883
5884 // Start performing drag, we will create a drag window and transfer touch to it.
5885 void performDrag() {
5886 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5887 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5888 {50, 50}))
5889 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5890
5891 // Window should receive motion event.
5892 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5893
5894 // The drag window covers the entire display
5895 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5896 mDispatcher->setInputWindows(
5897 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5898
5899 // Transfer touch focus to the drag window
5900 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5901 true /* isDragDrop */);
5902 mWindow->consumeMotionCancel();
5903 mDragWindow->consumeMotionDown();
5904 }
arthurhung6d4bed92021-03-17 11:59:33 +08005905
5906 // Start performing drag, we will create a drag window and transfer touch to it.
5907 void performStylusDrag() {
5908 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5909 injectMotionEvent(mDispatcher,
5910 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
5911 AINPUT_SOURCE_STYLUS)
5912 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
5913 .pointer(PointerBuilder(0,
5914 AMOTION_EVENT_TOOL_TYPE_STYLUS)
5915 .x(50)
5916 .y(50))
5917 .build()));
5918 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5919
5920 // The drag window covers the entire display
5921 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5922 mDispatcher->setInputWindows(
5923 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
5924
5925 // Transfer touch focus to the drag window
5926 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
5927 true /* isDragDrop */);
5928 mWindow->consumeMotionCancel();
5929 mDragWindow->consumeMotionDown();
5930 }
arthurhungb89ccb02020-12-30 16:19:01 +08005931};
5932
5933TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
5934 performDrag();
5935
5936 // Move on window.
5937 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5938 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5939 ADISPLAY_ID_DEFAULT, {50, 50}))
5940 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5941 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5942 mWindow->consumeDragEvent(false, 50, 50);
5943 mSecondWindow->assertNoEvents();
5944
5945 // Move to another window.
5946 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5947 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5948 ADISPLAY_ID_DEFAULT, {150, 50}))
5949 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5950 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5951 mWindow->consumeDragEvent(true, 150, 50);
5952 mSecondWindow->consumeDragEvent(false, 50, 50);
5953
5954 // Move back to original window.
5955 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5956 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5957 ADISPLAY_ID_DEFAULT, {50, 50}))
5958 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5959 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5960 mWindow->consumeDragEvent(false, 50, 50);
5961 mSecondWindow->consumeDragEvent(true, -50, 50);
5962
5963 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5964 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
5965 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5966 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5967 mWindow->assertNoEvents();
5968 mSecondWindow->assertNoEvents();
5969}
5970
arthurhungf452d0b2021-01-06 00:19:52 +08005971TEST_F(InputDispatcherDragTests, DragAndDrop) {
5972 performDrag();
5973
5974 // Move on window.
5975 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5976 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5977 ADISPLAY_ID_DEFAULT, {50, 50}))
5978 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5979 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5980 mWindow->consumeDragEvent(false, 50, 50);
5981 mSecondWindow->assertNoEvents();
5982
5983 // Move to another window.
5984 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5985 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
5986 ADISPLAY_ID_DEFAULT, {150, 50}))
5987 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5988 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
5989 mWindow->consumeDragEvent(true, 150, 50);
5990 mSecondWindow->consumeDragEvent(false, 50, 50);
5991
5992 // drop to another window.
5993 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5994 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5995 {150, 50}))
5996 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5997 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
5998 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
5999 mWindow->assertNoEvents();
6000 mSecondWindow->assertNoEvents();
6001}
6002
arthurhung6d4bed92021-03-17 11:59:33 +08006003TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6004 performStylusDrag();
6005
6006 // Move on window and keep button pressed.
6007 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6008 injectMotionEvent(mDispatcher,
6009 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6010 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6011 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6012 .x(50)
6013 .y(50))
6014 .build()))
6015 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6016 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6017 mWindow->consumeDragEvent(false, 50, 50);
6018 mSecondWindow->assertNoEvents();
6019
6020 // Move to another window and release button, expect to drop item.
6021 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6022 injectMotionEvent(mDispatcher,
6023 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6024 .buttonState(0)
6025 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6026 .x(150)
6027 .y(50))
6028 .build()))
6029 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6030 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6031 mWindow->assertNoEvents();
6032 mSecondWindow->assertNoEvents();
6033 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6034
6035 // nothing to the window.
6036 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6037 injectMotionEvent(mDispatcher,
6038 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6039 .buttonState(0)
6040 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6041 .x(150)
6042 .y(50))
6043 .build()))
6044 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6045 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6046 mWindow->assertNoEvents();
6047 mSecondWindow->assertNoEvents();
6048}
6049
Arthur Hung6d0571e2021-04-09 20:18:16 +08006050TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6051 performDrag();
6052
6053 // Set second window invisible.
6054 mSecondWindow->setVisible(false);
6055 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6056
6057 // Move on window.
6058 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6059 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6060 ADISPLAY_ID_DEFAULT, {50, 50}))
6061 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6062 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6063 mWindow->consumeDragEvent(false, 50, 50);
6064 mSecondWindow->assertNoEvents();
6065
6066 // Move to another window.
6067 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6068 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6069 ADISPLAY_ID_DEFAULT, {150, 50}))
6070 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6071 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6072 mWindow->consumeDragEvent(true, 150, 50);
6073 mSecondWindow->assertNoEvents();
6074
6075 // drop to another window.
6076 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6077 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6078 {150, 50}))
6079 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6080 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6081 mFakePolicy->assertDropTargetEquals(nullptr);
6082 mWindow->assertNoEvents();
6083 mSecondWindow->assertNoEvents();
6084}
6085
Vishnu Nair062a8672021-09-03 16:07:44 -07006086class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6087
6088TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6089 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6090 sp<FakeWindowHandle> window =
6091 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6092 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT);
6093 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6094 window->setFocusable(true);
6095 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6096 setFocusedWindow(window);
6097 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6098
6099 // With the flag set, window should not get any input
6100 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6101 mDispatcher->notifyKey(&keyArgs);
6102 window->assertNoEvents();
6103
6104 NotifyMotionArgs motionArgs =
6105 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6106 ADISPLAY_ID_DEFAULT);
6107 mDispatcher->notifyMotion(&motionArgs);
6108 window->assertNoEvents();
6109
6110 // With the flag cleared, the window should get input
6111 window->setInputFeatures({});
6112 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6113
6114 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6115 mDispatcher->notifyKey(&keyArgs);
6116 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6117
6118 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6119 ADISPLAY_ID_DEFAULT);
6120 mDispatcher->notifyMotion(&motionArgs);
6121 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6122 window->assertNoEvents();
6123}
6124
6125TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6126 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6127 std::make_shared<FakeApplicationHandle>();
6128 sp<FakeWindowHandle> obscuringWindow =
6129 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6130 ADISPLAY_ID_DEFAULT);
6131 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6132 obscuringWindow->setOwnerInfo(111, 111);
6133 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6134 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6135 sp<FakeWindowHandle> window =
6136 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6137 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6138 window->setOwnerInfo(222, 222);
6139 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6140 window->setFocusable(true);
6141 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6142 setFocusedWindow(window);
6143 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6144
6145 // With the flag set, window should not get any input
6146 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6147 mDispatcher->notifyKey(&keyArgs);
6148 window->assertNoEvents();
6149
6150 NotifyMotionArgs motionArgs =
6151 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6152 ADISPLAY_ID_DEFAULT);
6153 mDispatcher->notifyMotion(&motionArgs);
6154 window->assertNoEvents();
6155
6156 // With the flag cleared, the window should get input
6157 window->setInputFeatures({});
6158 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6159
6160 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6161 mDispatcher->notifyKey(&keyArgs);
6162 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6163
6164 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6165 ADISPLAY_ID_DEFAULT);
6166 mDispatcher->notifyMotion(&motionArgs);
6167 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6168 window->assertNoEvents();
6169}
6170
6171TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6172 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6173 std::make_shared<FakeApplicationHandle>();
6174 sp<FakeWindowHandle> obscuringWindow =
6175 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6176 ADISPLAY_ID_DEFAULT);
6177 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6178 obscuringWindow->setOwnerInfo(111, 111);
6179 obscuringWindow->setFlags(WindowInfo::Flag::NOT_TOUCHABLE);
6180 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6181 sp<FakeWindowHandle> window =
6182 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
6183 window->setInputFeatures(WindowInfo::Feature::DROP_INPUT_IF_OBSCURED);
6184 window->setOwnerInfo(222, 222);
6185 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6186 window->setFocusable(true);
6187 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6188 setFocusedWindow(window);
6189 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6190
6191 // With the flag set, window should not get any input
6192 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6193 mDispatcher->notifyKey(&keyArgs);
6194 window->assertNoEvents();
6195
6196 NotifyMotionArgs motionArgs =
6197 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6198 ADISPLAY_ID_DEFAULT);
6199 mDispatcher->notifyMotion(&motionArgs);
6200 window->assertNoEvents();
6201
6202 // When the window is no longer obscured because it went on top, it should get input
6203 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6204
6205 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6206 mDispatcher->notifyKey(&keyArgs);
6207 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6208
6209 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6210 ADISPLAY_ID_DEFAULT);
6211 mDispatcher->notifyMotion(&motionArgs);
6212 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6213 window->assertNoEvents();
6214}
6215
Antonio Kantekf16f2832021-09-28 04:39:20 +00006216class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6217protected:
6218 std::shared_ptr<FakeApplicationHandle> mApp;
6219 sp<FakeWindowHandle> mWindow;
6220 sp<FakeWindowHandle> mSecondWindow;
6221
6222 void SetUp() override {
6223 InputDispatcherTest::SetUp();
6224
6225 mApp = std::make_shared<FakeApplicationHandle>();
6226 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6227 mWindow->setFocusable(true);
6228 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6229 mSecondWindow->setFocusable(true);
6230
6231 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6232 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
6233
6234 setFocusedWindow(mWindow);
6235 mWindow->consumeFocusEvent(true);
6236 }
6237
Antonio Kantekea47acb2021-12-23 12:41:25 -08006238 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
6239 mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006240 mWindow->consumeTouchModeEvent(inTouchMode);
6241 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6242 }
6243};
6244
6245TEST_F(InputDispatcherTouchModeChangedTests, ChangeTouchModeOnFocusedWindow) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006246 const WindowInfo& windowInfo = *mWindow->getInfo();
6247 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6248 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006249}
6250
6251TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006252 const WindowInfo& windowInfo = *mWindow->getInfo();
6253 mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6254 windowInfo.ownerUid, /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006255 mWindow->assertNoEvents();
6256 mSecondWindow->assertNoEvents();
6257}
6258
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006259class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6260public:
6261 sp<FakeWindowHandle> createSpy(const Flags<WindowInfo::Flag> flags) {
6262 std::shared_ptr<FakeApplicationHandle> application =
6263 std::make_shared<FakeApplicationHandle>();
6264 std::string name = "Fake Spy ";
6265 name += std::to_string(mSpyCount++);
6266 sp<FakeWindowHandle> spy =
6267 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
6268 spy->setInputFeatures(WindowInfo::Feature::SPY);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006269 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006270 spy->addFlags(flags);
6271 return spy;
6272 }
6273
6274 sp<FakeWindowHandle> createForeground() {
6275 std::shared_ptr<FakeApplicationHandle> application =
6276 std::make_shared<FakeApplicationHandle>();
6277 sp<FakeWindowHandle> window =
6278 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
6279 window->addFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006280 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006281 return window;
6282 }
6283
6284private:
6285 int mSpyCount{0};
6286};
6287
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006288using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006289/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006290 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6291 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006292TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6293 ScopedSilentDeath _silentDeath;
6294
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006295 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6296 spy->setTrustedOverlay(false);
6297 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6298 ".* not a trusted overlay");
6299}
6300
6301/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006302 * Input injection into a display with a spy window but no foreground windows should succeed.
6303 */
6304TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
6305 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6306 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6307
6308 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6309 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6310 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6311 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6312}
6313
6314/**
6315 * Verify the order in which different input windows receive events. The touched foreground window
6316 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6317 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6318 * receive events before ones belows it.
6319 *
6320 * Here, we set up a scenario with four windows in the following Z order from the top:
6321 * spy1, spy2, window, spy3.
6322 * We then inject an event and verify that the foreground "window" receives it first, followed by
6323 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6324 * window.
6325 */
6326TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6327 auto window = createForeground();
6328 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6329 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6330 auto spy3 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6331 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6332 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6333 const size_t numChannels = channels.size();
6334
Michael Wright8e9a8562022-02-09 13:44:29 +00006335 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006336 if (!epollFd.ok()) {
6337 FAIL() << "Failed to create epoll fd";
6338 }
6339
6340 for (size_t i = 0; i < numChannels; i++) {
6341 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6342 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6343 FAIL() << "Failed to add fd to epoll";
6344 }
6345 }
6346
6347 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6348 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6349 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6350
6351 std::vector<size_t> eventOrder;
6352 std::vector<struct epoll_event> events(numChannels);
6353 for (;;) {
6354 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6355 (100ms).count());
6356 if (nFds < 0) {
6357 FAIL() << "Failed to call epoll_wait";
6358 }
6359 if (nFds == 0) {
6360 break; // epoll_wait timed out
6361 }
6362 for (int i = 0; i < nFds; i++) {
6363 ASSERT_EQ(EPOLLIN, events[i].events);
6364 eventOrder.push_back(events[i].data.u64);
6365 channels[i]->consumeMotionDown();
6366 }
6367 }
6368
6369 // Verify the order in which the events were received.
6370 EXPECT_EQ(3u, eventOrder.size());
6371 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6372 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6373 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6374}
6375
6376/**
6377 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6378 */
6379TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6380 auto window = createForeground();
6381 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCHABLE);
6382 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6383
6384 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6385 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6386 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6387 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6388 spy->assertNoEvents();
6389}
6390
6391/**
6392 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6393 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6394 * to the window.
6395 */
6396TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6397 auto window = createForeground();
6398 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6399 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6400 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6401
6402 // Inject an event outside the spy window's touchable region.
6403 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6404 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6405 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6406 window->consumeMotionDown();
6407 spy->assertNoEvents();
6408 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6409 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6410 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6411 window->consumeMotionUp();
6412 spy->assertNoEvents();
6413
6414 // Inject an event inside the spy window's touchable region.
6415 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6416 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6417 {5, 10}))
6418 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6419 window->consumeMotionDown();
6420 spy->consumeMotionDown();
6421}
6422
6423/**
6424 * A spy window that is a modal window will receive gestures outside of its frame and touchable
6425 * region.
6426 */
6427TEST_F(InputDispatcherSpyWindowTest, ModalWindow) {
6428 auto window = createForeground();
6429 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6430 // This spy window does not have the NOT_TOUCH_MODAL flag set.
6431 spy->setFrame(Rect{0, 0, 20, 20});
6432 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6433
6434 // Inject an event outside the spy window's frame and touchable region.
6435 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6436 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6437 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6438 window->consumeMotionDown();
6439 spy->consumeMotionDown();
6440}
6441
6442/**
6443 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006444 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006445 */
6446TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6447 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006448 window->setOwnerInfo(12, 34);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006449 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::WATCH_OUTSIDE_TOUCH);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006450 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006451 spy->setFrame(Rect{0, 0, 20, 20});
6452 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6453
6454 // Inject an event outside the spy window's frame and touchable region.
6455 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006456 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6457 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006458 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6459 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006460 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006461}
6462
6463/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006464 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6465 * any other windows - including other spy windows - will also be cancelled.
6466 */
6467TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6468 auto window = createForeground();
6469 auto spy1 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6470 auto spy2 = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6471 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6472
6473 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6474 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6475 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6476 window->consumeMotionDown();
6477 spy1->consumeMotionDown();
6478 spy2->consumeMotionDown();
6479
6480 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006481 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006482 spy2->assertNoEvents();
6483 spy1->consumeMotionCancel();
6484 window->consumeMotionCancel();
6485
6486 // The rest of the gesture should only be sent to the second spy window.
6487 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6488 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6489 ADISPLAY_ID_DEFAULT))
6490 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6491 spy2->consumeMotionMove();
6492 spy1->assertNoEvents();
6493 window->assertNoEvents();
6494}
6495
6496/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006497 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
6498 * in the middle of the gesture.
6499 */
6500TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
6501 auto window = createForeground();
6502 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6503 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6504
6505 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6506 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6507 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6508 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6509 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6510
6511 window->releaseChannel();
6512
6513 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6514
6515 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6516 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6517 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6518 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6519}
6520
6521/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006522 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
6523 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006524 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006525TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
6526 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006527 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006528 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
6529
6530 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6531
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006532 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006533 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6534 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6535 {100, 200}))
6536 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006537 spy->consumeMotionDown();
6538 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006539
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006540 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006541 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006542 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006543
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006544 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006545 const MotionEvent secondFingerDownEvent =
6546 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6547 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6548 AINPUT_SOURCE_TOUCHSCREEN)
6549 .displayId(ADISPLAY_ID_DEFAULT)
6550 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6551 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6552 .x(100)
6553 .y(200))
6554 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6555 .build();
6556 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6557 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6558 InputEventInjectionSync::WAIT_FOR_RESULT))
6559 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6560
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006561 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6562
6563 // Third finger goes down outside all windows, so injection should fail.
6564 const MotionEvent thirdFingerDownEvent =
6565 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6566 (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6567 AINPUT_SOURCE_TOUCHSCREEN)
6568 .displayId(ADISPLAY_ID_DEFAULT)
6569 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6570 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6571 .x(100)
6572 .y(200))
6573 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6574 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
6575 .build();
6576 ASSERT_EQ(InputEventInjectionResult::FAILED,
6577 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
6578 InputEventInjectionSync::WAIT_FOR_RESULT))
6579 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6580
6581 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006582 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006583}
6584
6585/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006586 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6587 * pointers that are down within its bounds.
6588 */
6589TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6590 auto windowLeft = createForeground();
6591 windowLeft->setFrame({0, 0, 100, 200});
6592 auto windowRight = createForeground();
6593 windowRight->setFrame({100, 0, 200, 200});
6594 auto spy = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6595 spy->setFrame({0, 0, 200, 200});
6596 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6597
6598 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6599 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6600 {50, 50}))
6601 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6602 windowLeft->consumeMotionDown();
6603 spy->consumeMotionDown();
6604
6605 const MotionEvent secondFingerDownEvent =
6606 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6607 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6608 AINPUT_SOURCE_TOUCHSCREEN)
6609 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6610 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6611 .pointer(
6612 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6613 .build();
6614 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6615 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6616 InputEventInjectionSync::WAIT_FOR_RESULT))
6617 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6618 windowRight->consumeMotionDown();
6619 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6620}
6621
6622/**
6623 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6624 * the spy should receive the second pointer with ACTION_DOWN.
6625 */
6626TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6627 auto window = createForeground();
6628 window->setFrame({0, 0, 200, 200});
6629 auto spyRight = createSpy(WindowInfo::Flag::NOT_TOUCH_MODAL);
6630 spyRight->setFrame({100, 0, 200, 200});
6631 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6632
6633 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6634 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6635 {50, 50}))
6636 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6637 window->consumeMotionDown();
6638 spyRight->assertNoEvents();
6639
6640 const MotionEvent secondFingerDownEvent =
6641 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6642 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6643 AINPUT_SOURCE_TOUCHSCREEN)
6644 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6645 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6646 .pointer(
6647 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6648 .build();
6649 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6650 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6651 InputEventInjectionSync::WAIT_FOR_RESULT))
6652 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6653 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6654 spyRight->consumeMotionDown();
6655}
6656
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006657/**
6658 * The spy window should not be able to affect whether or not touches are split. Only the foreground
6659 * windows should be allowed to control split touch.
6660 */
6661TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
6662 // Create a touch modal spy that spies on the entire display.
6663 // This spy window does not set the SPLIT_TOUCH flag. However, we still expect to split touches
6664 // because a foreground window has not disabled splitting.
6665 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6666
6667 // Create a non touch modal window that supports split touch.
6668 auto window = createForeground();
6669 window->setFrame(Rect(0, 0, 100, 100));
6670 window->setFlags(WindowInfo::Flag::NOT_TOUCH_MODAL | WindowInfo::Flag::SPLIT_TOUCH);
6671
6672 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6673
6674 // First finger down, no window touched.
6675 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6676 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6677 {100, 200}))
6678 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6679 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6680 window->assertNoEvents();
6681
6682 // Second finger down on window, the window should receive touch down.
6683 const MotionEvent secondFingerDownEvent =
6684 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6685 (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6686 AINPUT_SOURCE_TOUCHSCREEN)
6687 .displayId(ADISPLAY_ID_DEFAULT)
6688 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6689 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6690 .x(100)
6691 .y(200))
6692 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6693 .build();
6694 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6695 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6696 InputEventInjectionSync::WAIT_FOR_RESULT))
6697 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6698
6699 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6700 spy->consumeMotionPointerDown(1 /* pointerIndex */);
6701}
6702
6703/**
6704 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
6705 * do not receive key events.
6706 */
6707TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
6708 auto spy = createSpy(static_cast<WindowInfo::Flag>(0));
6709 spy->setFocusable(false);
6710
6711 auto window = createForeground();
6712 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6713 setFocusedWindow(window);
6714 window->consumeFocusEvent(true);
6715
6716 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6717 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6718 window->consumeKeyDown(ADISPLAY_ID_NONE);
6719
6720 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6721 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6722 window->consumeKeyUp(ADISPLAY_ID_NONE);
6723
6724 spy->assertNoEvents();
6725}
6726
Prabir Pradhand65552b2021-10-07 11:23:50 -07006727class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6728public:
6729 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6730 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6731 std::make_shared<FakeApplicationHandle>();
6732 sp<FakeWindowHandle> overlay =
6733 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6734 ADISPLAY_ID_DEFAULT);
6735 overlay->setFocusable(false);
6736 overlay->setOwnerInfo(111, 111);
6737 overlay->setFlags(WindowInfo::Flag::NOT_TOUCHABLE | WindowInfo::Flag::SPLIT_TOUCH);
6738 overlay->setInputFeatures(WindowInfo::Feature::INTERCEPTS_STYLUS);
6739 overlay->setTrustedOverlay(true);
6740
6741 std::shared_ptr<FakeApplicationHandle> application =
6742 std::make_shared<FakeApplicationHandle>();
6743 sp<FakeWindowHandle> window =
6744 new FakeWindowHandle(application, mDispatcher, "Application window",
6745 ADISPLAY_ID_DEFAULT);
6746 window->setFocusable(true);
6747 window->setOwnerInfo(222, 222);
6748 window->setFlags(WindowInfo::Flag::SPLIT_TOUCH);
6749
6750 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6751 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6752 setFocusedWindow(window);
6753 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6754 return {std::move(overlay), std::move(window)};
6755 }
6756
6757 void sendFingerEvent(int32_t action) {
6758 NotifyMotionArgs motionArgs =
6759 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6760 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6761 mDispatcher->notifyMotion(&motionArgs);
6762 }
6763
6764 void sendStylusEvent(int32_t action) {
6765 NotifyMotionArgs motionArgs =
6766 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6767 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6768 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6769 mDispatcher->notifyMotion(&motionArgs);
6770 }
6771};
6772
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006773using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
6774
6775TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
6776 ScopedSilentDeath _silentDeath;
6777
Prabir Pradhand65552b2021-10-07 11:23:50 -07006778 auto [overlay, window] = setupStylusOverlayScenario();
6779 overlay->setTrustedOverlay(false);
6780 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6781 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6782 ".* not a trusted overlay");
6783}
6784
6785TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6786 auto [overlay, window] = setupStylusOverlayScenario();
6787 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6788
6789 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6790 overlay->consumeMotionDown();
6791 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6792 overlay->consumeMotionUp();
6793
6794 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6795 window->consumeMotionDown();
6796 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6797 window->consumeMotionUp();
6798
6799 overlay->assertNoEvents();
6800 window->assertNoEvents();
6801}
6802
6803TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6804 auto [overlay, window] = setupStylusOverlayScenario();
6805 overlay->setInputFeatures(overlay->getInfo()->inputFeatures | WindowInfo::Feature::SPY);
6806 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6807
6808 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6809 overlay->consumeMotionDown();
6810 window->consumeMotionDown();
6811 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6812 overlay->consumeMotionUp();
6813 window->consumeMotionUp();
6814
6815 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6816 window->consumeMotionDown();
6817 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6818 window->consumeMotionUp();
6819
6820 overlay->assertNoEvents();
6821 window->assertNoEvents();
6822}
6823
Antonio Kantekea47acb2021-12-23 12:41:25 -08006824// TODO(b/198487159): Add permission tests for touch mode switch once the validation is put in
6825// place.
6826
Garfield Tane84e6f92019-08-29 17:28:41 -07006827} // namespace android::inputdispatcher