blob: 112b19a8fa8656b57db9a84be161fc6423383ac8 [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;
Garfield Tan1c7bc862020-01-28 13:24:04 -080042
Garfield Tane84e6f92019-08-29 17:28:41 -070043namespace android::inputdispatcher {
Michael Wrightd02c5b62014-02-10 15:10:22 -080044
Dominik Laskowski2f01d772022-03-23 16:01:29 -070045using namespace ftl::flag_operators;
46
Michael Wrightd02c5b62014-02-10 15:10:22 -080047// An arbitrary time value.
Prabir Pradhan4df80f52022-04-05 18:33:16 +000048static const nsecs_t ARBITRARY_TIME = 1234;
Michael Wrightd02c5b62014-02-10 15:10:22 -080049
50// An arbitrary device id.
Prabir Pradhan4df80f52022-04-05 18:33:16 +000051static const int32_t DEVICE_ID = 1;
Michael Wrightd02c5b62014-02-10 15:10:22 -080052
Jeff Brownf086ddb2014-02-11 14:28:48 -080053// An arbitrary display id.
Arthur Hungabbb9d82021-09-01 14:52:30 +000054static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
55static constexpr int32_t SECOND_DISPLAY_ID = 1;
Jeff Brownf086ddb2014-02-11 14:28:48 -080056
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -080057static constexpr int32_t POINTER_1_DOWN =
58 AMOTION_EVENT_ACTION_POINTER_DOWN | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
59static constexpr int32_t POINTER_1_UP =
60 AMOTION_EVENT_ACTION_POINTER_UP | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
61
Prabir Pradhan4df80f52022-04-05 18:33:16 +000062// An arbitrary injector pid / uid pair that has permission to inject events.
63static const int32_t INJECTOR_PID = 999;
64static const int32_t INJECTOR_UID = 1001;
Michael Wrightd02c5b62014-02-10 15:10:22 -080065
Siarhei Vishniakou58cfc602020-12-14 23:21:30 +000066// An arbitrary pid of the gesture monitor window
67static constexpr int32_t MONITOR_PID = 2001;
68
Siarhei Vishniakou289e9242022-02-15 14:50:16 -080069static constexpr std::chrono::duration STALE_EVENT_TIMEOUT = 1000ms;
70
chaviwd1c23182019-12-20 18:44:56 -080071struct PointF {
72 float x;
73 float y;
74};
Michael Wrightd02c5b62014-02-10 15:10:22 -080075
Gang Wang342c9272020-01-13 13:15:04 -050076/**
77 * Return a DOWN key event with KEYCODE_A.
78 */
79static KeyEvent getTestKeyEvent() {
80 KeyEvent event;
81
Garfield Tanfbe732e2020-01-24 11:26:14 -080082 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
83 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
84 ARBITRARY_TIME, ARBITRARY_TIME);
Gang Wang342c9272020-01-13 13:15:04 -050085 return event;
86}
87
Siarhei Vishniakouca205502021-07-16 21:31:58 +000088static void assertMotionAction(int32_t expectedAction, int32_t receivedAction) {
89 ASSERT_EQ(expectedAction, receivedAction)
90 << "expected " << MotionEvent::actionToString(expectedAction) << ", got "
91 << MotionEvent::actionToString(receivedAction);
92}
93
Michael Wrightd02c5b62014-02-10 15:10:22 -080094// --- FakeInputDispatcherPolicy ---
95
96class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
97 InputDispatcherConfiguration mConfig;
98
Prabir Pradhanedd96402022-02-15 01:46:16 -080099 using AnrResult = std::pair<sp<IBinder>, int32_t /*pid*/>;
100
Michael Wrightd02c5b62014-02-10 15:10:22 -0800101protected:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000102 virtual ~FakeInputDispatcherPolicy() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800103
104public:
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000105 FakeInputDispatcherPolicy() {}
Jackal Guof9696682018-10-05 12:23:23 +0800106
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800107 void assertFilterInputEventWasCalled(const NotifyKeyArgs& args) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700108 assertFilterInputEventWasCalledInternal([&args](const InputEvent& event) {
109 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_KEY);
110 EXPECT_EQ(event.getDisplayId(), args.displayId);
111
112 const auto& keyEvent = static_cast<const KeyEvent&>(event);
113 EXPECT_EQ(keyEvent.getEventTime(), args.eventTime);
114 EXPECT_EQ(keyEvent.getAction(), args.action);
115 });
Jackal Guof9696682018-10-05 12:23:23 +0800116 }
117
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700118 void assertFilterInputEventWasCalled(const NotifyMotionArgs& args, vec2 point) {
119 assertFilterInputEventWasCalledInternal([&](const InputEvent& event) {
120 ASSERT_EQ(event.getType(), AINPUT_EVENT_TYPE_MOTION);
121 EXPECT_EQ(event.getDisplayId(), args.displayId);
122
123 const auto& motionEvent = static_cast<const MotionEvent&>(event);
124 EXPECT_EQ(motionEvent.getEventTime(), args.eventTime);
125 EXPECT_EQ(motionEvent.getAction(), args.action);
126 EXPECT_EQ(motionEvent.getX(0), point.x);
127 EXPECT_EQ(motionEvent.getY(0), point.y);
128 EXPECT_EQ(motionEvent.getRawX(0), point.x);
129 EXPECT_EQ(motionEvent.getRawY(0), point.y);
130 });
Jackal Guof9696682018-10-05 12:23:23 +0800131 }
132
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700133 void assertFilterInputEventWasNotCalled() {
134 std::scoped_lock lock(mLock);
135 ASSERT_EQ(nullptr, mFilteredEvent);
136 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800137
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800138 void assertNotifyConfigurationChangedWasCalled(nsecs_t when) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700139 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800140 ASSERT_TRUE(mConfigurationChangedTime)
141 << "Timed out waiting for configuration changed call";
142 ASSERT_EQ(*mConfigurationChangedTime, when);
143 mConfigurationChangedTime = std::nullopt;
144 }
145
146 void assertNotifySwitchWasCalled(const NotifySwitchArgs& args) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700147 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800148 ASSERT_TRUE(mLastNotifySwitch);
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800149 // We do not check id because it is not exposed to the policy
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800150 EXPECT_EQ(args.eventTime, mLastNotifySwitch->eventTime);
151 EXPECT_EQ(args.policyFlags, mLastNotifySwitch->policyFlags);
152 EXPECT_EQ(args.switchValues, mLastNotifySwitch->switchValues);
153 EXPECT_EQ(args.switchMask, mLastNotifySwitch->switchMask);
154 mLastNotifySwitch = std::nullopt;
155 }
156
chaviwfd6d3512019-03-25 13:23:49 -0700157 void assertOnPointerDownEquals(const sp<IBinder>& touchedToken) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700158 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800159 ASSERT_EQ(touchedToken, mOnPointerDownToken);
160 mOnPointerDownToken.clear();
161 }
162
163 void assertOnPointerDownWasNotCalled() {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700164 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800165 ASSERT_TRUE(mOnPointerDownToken == nullptr)
166 << "Expected onPointerDownOutsideFocus to not have been called";
chaviwfd6d3512019-03-25 13:23:49 -0700167 }
168
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700169 // This function must be called soon after the expected ANR timer starts,
170 // because we are also checking how much time has passed.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500171 void assertNotifyNoFocusedWindowAnrWasCalled(
Chris Yea209fde2020-07-22 13:54:51 -0700172 std::chrono::nanoseconds timeout,
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500173 const std::shared_ptr<InputApplicationHandle>& expectedApplication) {
Prabir Pradhanedd96402022-02-15 01:46:16 -0800174 std::unique_lock lock(mLock);
175 android::base::ScopedLockAssertion assumeLocked(mLock);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500176 std::shared_ptr<InputApplicationHandle> application;
Prabir Pradhanedd96402022-02-15 01:46:16 -0800177 ASSERT_NO_FATAL_FAILURE(
178 application = getAnrTokenLockedInterruptible(timeout, mAnrApplications, lock));
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500179 ASSERT_EQ(expectedApplication, application);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700180 }
181
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000182 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
Prabir Pradhanedd96402022-02-15 01:46:16 -0800183 const sp<WindowInfoHandle>& window) {
184 LOG_ALWAYS_FATAL_IF(window == nullptr, "window should not be null");
185 assertNotifyWindowUnresponsiveWasCalled(timeout, window->getToken(),
186 window->getInfo()->ownerPid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500187 }
188
Prabir Pradhanedd96402022-02-15 01:46:16 -0800189 void assertNotifyWindowUnresponsiveWasCalled(std::chrono::nanoseconds timeout,
190 const sp<IBinder>& expectedToken,
191 int32_t expectedPid) {
192 std::unique_lock lock(mLock);
193 android::base::ScopedLockAssertion assumeLocked(mLock);
194 AnrResult result;
195 ASSERT_NO_FATAL_FAILURE(result =
196 getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock));
197 const auto& [token, pid] = result;
198 ASSERT_EQ(expectedToken, token);
199 ASSERT_EQ(expectedPid, pid);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500200 }
201
Prabir Pradhanedd96402022-02-15 01:46:16 -0800202 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000203 sp<IBinder> getUnresponsiveWindowToken(std::chrono::nanoseconds timeout) {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500204 std::unique_lock lock(mLock);
205 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800206 AnrResult result = getAnrTokenLockedInterruptible(timeout, mAnrWindows, lock);
207 const auto& [token, _] = result;
208 return token;
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000209 }
210
Prabir Pradhanedd96402022-02-15 01:46:16 -0800211 void assertNotifyWindowResponsiveWasCalled(const sp<IBinder>& expectedToken,
212 int32_t expectedPid) {
213 std::unique_lock lock(mLock);
214 android::base::ScopedLockAssertion assumeLocked(mLock);
215 AnrResult result;
216 ASSERT_NO_FATAL_FAILURE(
217 result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock));
218 const auto& [token, pid] = result;
219 ASSERT_EQ(expectedToken, token);
220 ASSERT_EQ(expectedPid, pid);
221 }
222
223 /** Wrap call with ASSERT_NO_FATAL_FAILURE() to ensure the return value is valid. */
Siarhei Vishniakou3c63fa42020-12-15 02:59:54 +0000224 sp<IBinder> getResponsiveWindowToken() {
225 std::unique_lock lock(mLock);
226 android::base::ScopedLockAssertion assumeLocked(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800227 AnrResult result = getAnrTokenLockedInterruptible(0s, mResponsiveWindows, lock);
228 const auto& [token, _] = result;
229 return token;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700230 }
231
232 void assertNotifyAnrWasNotCalled() {
233 std::scoped_lock lock(mLock);
234 ASSERT_TRUE(mAnrApplications.empty());
Prabir Pradhanedd96402022-02-15 01:46:16 -0800235 ASSERT_TRUE(mAnrWindows.empty());
236 ASSERT_TRUE(mResponsiveWindows.empty())
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500237 << "ANR was not called, but please also consume the 'connection is responsive' "
238 "signal";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700239 }
240
Garfield Tan1c7bc862020-01-28 13:24:04 -0800241 void setKeyRepeatConfiguration(nsecs_t timeout, nsecs_t delay) {
242 mConfig.keyRepeatTimeout = timeout;
243 mConfig.keyRepeatDelay = delay;
244 }
245
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000246 PointerCaptureRequest assertSetPointerCaptureCalled(bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -0800247 std::unique_lock lock(mLock);
248 base::ScopedLockAssertion assumeLocked(mLock);
249
250 if (!mPointerCaptureChangedCondition.wait_for(lock, 100ms,
251 [this, enabled]() REQUIRES(mLock) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000252 return mPointerCaptureRequest->enable ==
Prabir Pradhan99987712020-11-10 18:43:05 -0800253 enabled;
254 })) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000255 ADD_FAILURE() << "Timed out waiting for setPointerCapture(" << enabled
256 << ") to be called.";
257 return {};
Prabir Pradhan99987712020-11-10 18:43:05 -0800258 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000259 auto request = *mPointerCaptureRequest;
260 mPointerCaptureRequest.reset();
261 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -0800262 }
263
264 void assertSetPointerCaptureNotCalled() {
265 std::unique_lock lock(mLock);
266 base::ScopedLockAssertion assumeLocked(mLock);
267
268 if (mPointerCaptureChangedCondition.wait_for(lock, 100ms) != std::cv_status::timeout) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000269 FAIL() << "Expected setPointerCapture(request) to not be called, but was called. "
Prabir Pradhan99987712020-11-10 18:43:05 -0800270 "enabled = "
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000271 << std::to_string(mPointerCaptureRequest->enable);
Prabir Pradhan99987712020-11-10 18:43:05 -0800272 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000273 mPointerCaptureRequest.reset();
Prabir Pradhan99987712020-11-10 18:43:05 -0800274 }
275
arthurhungf452d0b2021-01-06 00:19:52 +0800276 void assertDropTargetEquals(const sp<IBinder>& targetToken) {
277 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800278 ASSERT_TRUE(mNotifyDropWindowWasCalled);
arthurhungf452d0b2021-01-06 00:19:52 +0800279 ASSERT_EQ(targetToken, mDropTargetWindowToken);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800280 mNotifyDropWindowWasCalled = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800281 }
282
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800283 void assertNotifyInputChannelBrokenWasCalled(const sp<IBinder>& token) {
284 std::unique_lock lock(mLock);
285 base::ScopedLockAssertion assumeLocked(mLock);
286 std::optional<sp<IBinder>> receivedToken =
287 getItemFromStorageLockedInterruptible(100ms, mBrokenInputChannels, lock,
288 mNotifyInputChannelBroken);
289 ASSERT_TRUE(receivedToken.has_value());
290 ASSERT_EQ(token, *receivedToken);
291 }
292
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800293 /**
294 * Set policy timeout. A value of zero means next key will not be intercepted.
295 */
296 void setInterceptKeyTimeout(std::chrono::milliseconds timeout) {
297 mInterceptKeyTimeout = timeout;
298 }
299
Michael Wrightd02c5b62014-02-10 15:10:22 -0800300private:
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700301 std::mutex mLock;
302 std::unique_ptr<InputEvent> mFilteredEvent GUARDED_BY(mLock);
303 std::optional<nsecs_t> mConfigurationChangedTime GUARDED_BY(mLock);
304 sp<IBinder> mOnPointerDownToken GUARDED_BY(mLock);
305 std::optional<NotifySwitchArgs> mLastNotifySwitch GUARDED_BY(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800306
Prabir Pradhan99987712020-11-10 18:43:05 -0800307 std::condition_variable mPointerCaptureChangedCondition;
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000308
309 std::optional<PointerCaptureRequest> mPointerCaptureRequest GUARDED_BY(mLock);
Prabir Pradhan99987712020-11-10 18:43:05 -0800310
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700311 // ANR handling
Chris Yea209fde2020-07-22 13:54:51 -0700312 std::queue<std::shared_ptr<InputApplicationHandle>> mAnrApplications GUARDED_BY(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800313 std::queue<AnrResult> mAnrWindows GUARDED_BY(mLock);
314 std::queue<AnrResult> mResponsiveWindows GUARDED_BY(mLock);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700315 std::condition_variable mNotifyAnr;
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800316 std::queue<sp<IBinder>> mBrokenInputChannels GUARDED_BY(mLock);
317 std::condition_variable mNotifyInputChannelBroken;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700318
arthurhungf452d0b2021-01-06 00:19:52 +0800319 sp<IBinder> mDropTargetWindowToken GUARDED_BY(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800320 bool mNotifyDropWindowWasCalled GUARDED_BY(mLock) = false;
arthurhungf452d0b2021-01-06 00:19:52 +0800321
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800322 std::chrono::milliseconds mInterceptKeyTimeout = 0ms;
323
Prabir Pradhanedd96402022-02-15 01:46:16 -0800324 // All three ANR-related callbacks behave the same way, so we use this generic function to wait
325 // for a specific container to become non-empty. When the container is non-empty, return the
326 // first entry from the container and erase it.
327 template <class T>
328 T getAnrTokenLockedInterruptible(std::chrono::nanoseconds timeout, std::queue<T>& storage,
329 std::unique_lock<std::mutex>& lock) REQUIRES(mLock) {
330 // If there is an ANR, Dispatcher won't be idle because there are still events
331 // in the waitQueue that we need to check on. So we can't wait for dispatcher to be idle
332 // before checking if ANR was called.
333 // Since dispatcher is not guaranteed to call notifyNoFocusedWindowAnr right away, we need
334 // to provide it some time to act. 100ms seems reasonable.
335 std::chrono::duration timeToWait = timeout + 100ms; // provide some slack
336 const std::chrono::time_point start = std::chrono::steady_clock::now();
337 std::optional<T> token =
338 getItemFromStorageLockedInterruptible(timeToWait, storage, lock, mNotifyAnr);
339 if (!token.has_value()) {
340 ADD_FAILURE() << "Did not receive the ANR callback";
341 return {};
342 }
343
344 const std::chrono::duration waited = std::chrono::steady_clock::now() - start;
345 // Ensure that the ANR didn't get raised too early. We can't be too strict here because
346 // the dispatcher started counting before this function was called
347 if (std::chrono::abs(timeout - waited) > 100ms) {
348 ADD_FAILURE() << "ANR was raised too early or too late. Expected "
349 << std::chrono::duration_cast<std::chrono::milliseconds>(timeout).count()
350 << "ms, but waited "
351 << std::chrono::duration_cast<std::chrono::milliseconds>(waited).count()
352 << "ms instead";
353 }
354 return *token;
355 }
356
357 template <class T>
358 std::optional<T> getItemFromStorageLockedInterruptible(std::chrono::nanoseconds timeout,
359 std::queue<T>& storage,
360 std::unique_lock<std::mutex>& lock,
361 std::condition_variable& condition)
362 REQUIRES(mLock) {
363 condition.wait_for(lock, timeout,
364 [&storage]() REQUIRES(mLock) { return !storage.empty(); });
365 if (storage.empty()) {
366 ADD_FAILURE() << "Did not receive the expected callback";
367 return std::nullopt;
368 }
369 T item = storage.front();
370 storage.pop();
371 return std::make_optional(item);
372 }
373
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600374 void notifyConfigurationChanged(nsecs_t when) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700375 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800376 mConfigurationChangedTime = when;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800377 }
378
Prabir Pradhanedd96402022-02-15 01:46:16 -0800379 void notifyWindowUnresponsive(const sp<IBinder>& connectionToken, std::optional<int32_t> pid,
380 const std::string&) override {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700381 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800382 ASSERT_TRUE(pid.has_value());
383 mAnrWindows.push({connectionToken, *pid});
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700384 mNotifyAnr.notify_all();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500385 }
386
Prabir Pradhanedd96402022-02-15 01:46:16 -0800387 void notifyWindowResponsive(const sp<IBinder>& connectionToken,
388 std::optional<int32_t> pid) override {
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500389 std::scoped_lock lock(mLock);
Prabir Pradhanedd96402022-02-15 01:46:16 -0800390 ASSERT_TRUE(pid.has_value());
391 mResponsiveWindows.push({connectionToken, *pid});
Siarhei Vishniakou234129c2020-10-22 22:28:12 -0500392 mNotifyAnr.notify_all();
393 }
394
395 void notifyNoFocusedWindowAnr(
396 const std::shared_ptr<InputApplicationHandle>& applicationHandle) override {
397 std::scoped_lock lock(mLock);
398 mAnrApplications.push(applicationHandle);
399 mNotifyAnr.notify_all();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800400 }
401
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -0800402 void notifyInputChannelBroken(const sp<IBinder>& connectionToken) override {
403 std::scoped_lock lock(mLock);
404 mBrokenInputChannels.push(connectionToken);
405 mNotifyInputChannelBroken.notify_all();
406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800407
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600408 void notifyFocusChanged(const sp<IBinder>&, const sp<IBinder>&) override {}
Robert Carr740167f2018-10-11 19:03:41 -0700409
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600410 void notifyUntrustedTouch(const std::string& obscuringPackage) override {}
Chris Yef59a2f42020-10-16 12:55:26 -0700411 void notifySensorEvent(int32_t deviceId, InputDeviceSensorType sensorType,
412 InputDeviceSensorAccuracy accuracy, nsecs_t timestamp,
413 const std::vector<float>& values) override {}
414
415 void notifySensorAccuracy(int deviceId, InputDeviceSensorType sensorType,
416 InputDeviceSensorAccuracy accuracy) override {}
Bernardo Rufino2e1f6512020-10-08 13:42:07 +0000417
Chris Yefb552902021-02-03 17:18:37 -0800418 void notifyVibratorState(int32_t deviceId, bool isOn) override {}
419
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600420 void getDispatcherConfiguration(InputDispatcherConfiguration* outConfig) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800421 *outConfig = mConfig;
422 }
423
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600424 bool filterInputEvent(const InputEvent* inputEvent, uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700425 std::scoped_lock lock(mLock);
Jackal Guof9696682018-10-05 12:23:23 +0800426 switch (inputEvent->getType()) {
427 case AINPUT_EVENT_TYPE_KEY: {
428 const KeyEvent* keyEvent = static_cast<const KeyEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800429 mFilteredEvent = std::make_unique<KeyEvent>(*keyEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800430 break;
431 }
432
433 case AINPUT_EVENT_TYPE_MOTION: {
434 const MotionEvent* motionEvent = static_cast<const MotionEvent*>(inputEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800435 mFilteredEvent = std::make_unique<MotionEvent>(*motionEvent);
Jackal Guof9696682018-10-05 12:23:23 +0800436 break;
437 }
438 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800439 return true;
440 }
441
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800442 void interceptKeyBeforeQueueing(const KeyEvent* inputEvent, uint32_t&) override {
443 if (inputEvent->getAction() == AKEY_EVENT_ACTION_UP) {
444 // Clear intercept state when we handled the event.
445 mInterceptKeyTimeout = 0ms;
446 }
447 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600449 void interceptMotionBeforeQueueing(int32_t, nsecs_t, uint32_t&) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800450
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600451 nsecs_t interceptKeyBeforeDispatching(const sp<IBinder>&, const KeyEvent*, uint32_t) override {
Arthur Hung2ee6d0b2022-03-03 20:19:38 +0800452 nsecs_t delay = std::chrono::nanoseconds(mInterceptKeyTimeout).count();
453 // Clear intercept state so we could dispatch the event in next wake.
454 mInterceptKeyTimeout = 0ms;
455 return delay;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800456 }
457
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600458 bool dispatchUnhandledKey(const sp<IBinder>&, const KeyEvent*, uint32_t, KeyEvent*) override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800459 return false;
460 }
461
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600462 void notifySwitch(nsecs_t when, uint32_t switchValues, uint32_t switchMask,
463 uint32_t policyFlags) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700464 std::scoped_lock lock(mLock);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800465 /** We simply reconstruct NotifySwitchArgs in policy because InputDispatcher is
466 * essentially a passthrough for notifySwitch.
467 */
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800468 mLastNotifySwitch = NotifySwitchArgs(1 /*id*/, when, policyFlags, switchValues, switchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800469 }
470
Sean Stoutb4e0a592021-02-23 07:34:53 -0800471 void pokeUserActivity(nsecs_t, int32_t, int32_t) override {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472
Prabir Pradhan4df80f52022-04-05 18:33:16 +0000473 bool checkInjectEventsPermissionNonReentrant(int32_t pid, int32_t uid) override {
474 return pid == INJECTOR_PID && uid == INJECTOR_UID;
475 }
476
Siarhei Vishniakou2b4782c2020-11-07 01:51:18 -0600477 void onPointerDownOutsideFocus(const sp<IBinder>& newToken) override {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700478 std::scoped_lock lock(mLock);
chaviwfd6d3512019-03-25 13:23:49 -0700479 mOnPointerDownToken = newToken;
480 }
481
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000482 void setPointerCapture(const PointerCaptureRequest& request) override {
Prabir Pradhan99987712020-11-10 18:43:05 -0800483 std::scoped_lock lock(mLock);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000484 mPointerCaptureRequest = {request};
Prabir Pradhan99987712020-11-10 18:43:05 -0800485 mPointerCaptureChangedCondition.notify_all();
486 }
487
arthurhungf452d0b2021-01-06 00:19:52 +0800488 void notifyDropWindow(const sp<IBinder>& token, float x, float y) override {
489 std::scoped_lock lock(mLock);
Arthur Hung6d0571e2021-04-09 20:18:16 +0800490 mNotifyDropWindowWasCalled = true;
arthurhungf452d0b2021-01-06 00:19:52 +0800491 mDropTargetWindowToken = token;
492 }
493
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700494 void assertFilterInputEventWasCalledInternal(
495 const std::function<void(const InputEvent&)>& verify) {
Siarhei Vishniakoucd899e82020-05-08 09:24:29 -0700496 std::scoped_lock lock(mLock);
Siarhei Vishniakoud99e1b62019-11-26 11:01:06 -0800497 ASSERT_NE(nullptr, mFilteredEvent) << "Expected filterInputEvent() to have been called.";
Prabir Pradhan81420cc2021-09-06 10:28:50 -0700498 verify(*mFilteredEvent);
Siarhei Vishniakou8935a802019-11-15 16:41:44 -0800499 mFilteredEvent = nullptr;
Jackal Guof9696682018-10-05 12:23:23 +0800500 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800501};
502
Michael Wrightd02c5b62014-02-10 15:10:22 -0800503// --- InputDispatcherTest ---
504
505class InputDispatcherTest : public testing::Test {
506protected:
507 sp<FakeInputDispatcherPolicy> mFakePolicy;
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700508 std::unique_ptr<InputDispatcher> mDispatcher;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800509
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000510 void SetUp() override {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800511 mFakePolicy = new FakeInputDispatcherPolicy();
Siarhei Vishniakou289e9242022-02-15 14:50:16 -0800512 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy, STALE_EVENT_TIMEOUT);
Arthur Hungb92218b2018-08-14 12:00:21 +0800513 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000514 // Start InputDispatcher thread
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700515 ASSERT_EQ(OK, mDispatcher->start());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516 }
517
Siarhei Vishniakouf2652122021-03-05 21:39:46 +0000518 void TearDown() override {
Prabir Pradhan3608aad2019-10-02 17:08:26 -0700519 ASSERT_EQ(OK, mDispatcher->stop());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800520 mFakePolicy.clear();
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700521 mDispatcher.reset();
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700523
524 /**
525 * Used for debugging when writing the test
526 */
527 void dumpDispatcherState() {
528 std::string dump;
529 mDispatcher->dump(dump);
530 std::stringstream ss(dump);
531 std::string to;
532
533 while (std::getline(ss, to, '\n')) {
534 ALOGE("%s", to.c_str());
535 }
536 }
Vishnu Nair958da932020-08-21 17:12:37 -0700537
chaviw3277faf2021-05-19 16:45:23 -0500538 void setFocusedWindow(const sp<WindowInfoHandle>& window,
539 const sp<WindowInfoHandle>& focusedWindow = nullptr) {
Vishnu Nair958da932020-08-21 17:12:37 -0700540 FocusRequest request;
541 request.token = window->getToken();
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +0000542 request.windowName = window->getName();
Vishnu Nair958da932020-08-21 17:12:37 -0700543 if (focusedWindow) {
544 request.focusedToken = focusedWindow->getToken();
545 }
546 request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
547 request.displayId = window->getInfo()->displayId;
548 mDispatcher->setFocusedWindow(request);
549 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550};
551
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesKeyEvents) {
553 KeyEvent event;
554
555 // Rejects undefined key actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800556 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
557 INVALID_HMAC,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600558 /*action*/ -1, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0, ARBITRARY_TIME,
559 ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800560 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan4df80f52022-04-05 18:33:16 +0000561 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
562 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800563 << "Should reject key events with undefined action.";
564
565 // Rejects ACTION_MULTIPLE since it is not supported despite being defined in the API.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800566 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
567 INVALID_HMAC, AKEY_EVENT_ACTION_MULTIPLE, 0, AKEYCODE_A, KEY_A, AMETA_NONE, 0,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600568 ARBITRARY_TIME, ARBITRARY_TIME);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800569 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan4df80f52022-04-05 18:33:16 +0000570 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
571 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800572 << "Should reject key events with ACTION_MULTIPLE.";
573}
574
575TEST_F(InputDispatcherTest, InjectInputEvent_ValidatesMotionEvents) {
576 MotionEvent event;
577 PointerProperties pointerProperties[MAX_POINTERS + 1];
578 PointerCoords pointerCoords[MAX_POINTERS + 1];
Siarhei Vishniakou01747382022-01-20 13:23:27 -0800579 for (size_t i = 0; i <= MAX_POINTERS; i++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800580 pointerProperties[i].clear();
581 pointerProperties[i].id = i;
582 pointerCoords[i].clear();
583 }
584
Siarhei Vishniakou49e59222018-12-28 18:17:15 -0800585 // Some constants commonly used below
586 constexpr int32_t source = AINPUT_SOURCE_TOUCHSCREEN;
587 constexpr int32_t edgeFlags = AMOTION_EVENT_EDGE_FLAG_NONE;
588 constexpr int32_t metaState = AMETA_NONE;
589 constexpr MotionClassification classification = MotionClassification::NONE;
590
chaviw9eaa22c2020-07-01 16:21:27 -0700591 ui::Transform identityTransform;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800592 // Rejects undefined motion actions.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800593 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
chaviw9eaa22c2020-07-01 16:21:27 -0700594 /*action*/ -1, 0, 0, edgeFlags, metaState, 0, classification,
595 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700596 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
597 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700598 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800599 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan4df80f52022-04-05 18:33:16 +0000600 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
601 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800602 << "Should reject motion events with undefined action.";
603
604 // Rejects pointer down with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800605 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800606 POINTER_1_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
607 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
608 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
609 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500610 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800611 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan4df80f52022-04-05 18:33:16 +0000612 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
613 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800614 << "Should reject motion events with pointer down index too large.";
615
Garfield Tanfbe732e2020-01-24 11:26:14 -0800616 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700617 AMOTION_EVENT_ACTION_POINTER_DOWN |
618 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700619 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
620 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700621 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500622 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800623 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan4df80f52022-04-05 18:33:16 +0000624 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
625 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800626 << "Should reject motion events with pointer down index too small.";
627
628 // Rejects pointer up with invalid index.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800629 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -0800630 POINTER_1_UP, 0, 0, edgeFlags, metaState, 0, classification, identityTransform,
631 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
632 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
633 ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500634 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800635 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan4df80f52022-04-05 18:33:16 +0000636 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
637 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800638 << "Should reject motion events with pointer up index too large.";
639
Garfield Tanfbe732e2020-01-24 11:26:14 -0800640 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
Garfield Tan00f511d2019-06-12 16:55:40 -0700641 AMOTION_EVENT_ACTION_POINTER_UP |
642 (~0U << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
chaviw9eaa22c2020-07-01 16:21:27 -0700643 0, 0, edgeFlags, metaState, 0, classification, identityTransform, 0, 0,
644 AMOTION_EVENT_INVALID_CURSOR_POSITION, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700645 identityTransform, ARBITRARY_TIME, ARBITRARY_TIME,
chaviw3277faf2021-05-19 16:45:23 -0500646 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800647 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan4df80f52022-04-05 18:33:16 +0000648 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
649 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650 << "Should reject motion events with pointer up index too small.";
651
652 // Rejects motion events with invalid number of pointers.
Garfield Tanfbe732e2020-01-24 11:26:14 -0800653 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
654 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700655 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700656 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
657 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700658 /*pointerCount*/ 0, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800659 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan4df80f52022-04-05 18:33:16 +0000660 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
661 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800662 << "Should reject motion events with 0 pointers.";
663
Garfield Tanfbe732e2020-01-24 11:26:14 -0800664 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
665 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700666 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700667 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
668 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700669 /*pointerCount*/ MAX_POINTERS + 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800670 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan4df80f52022-04-05 18:33:16 +0000671 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
672 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800673 << "Should reject motion events with more than MAX_POINTERS pointers.";
674
675 // Rejects motion events with invalid pointer ids.
676 pointerProperties[0].id = -1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800677 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
678 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700679 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700680 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
681 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700682 /*pointerCount*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800683 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan4df80f52022-04-05 18:33:16 +0000684 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
685 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800686 << "Should reject motion events with pointer ids less than 0.";
687
688 pointerProperties[0].id = MAX_POINTER_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*/ 1, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800695 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan4df80f52022-04-05 18:33:16 +0000696 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
697 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 << "Should reject motion events with pointer ids greater than MAX_POINTER_ID.";
699
700 // Rejects motion events with duplicate pointer ids.
701 pointerProperties[0].id = 1;
702 pointerProperties[1].id = 1;
Garfield Tanfbe732e2020-01-24 11:26:14 -0800703 event.initialize(InputEvent::nextId(), DEVICE_ID, source, DISPLAY_ID, INVALID_HMAC,
704 AMOTION_EVENT_ACTION_DOWN, 0, 0, edgeFlags, metaState, 0, classification,
chaviw9eaa22c2020-07-01 16:21:27 -0700705 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700706 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, ARBITRARY_TIME,
707 ARBITRARY_TIME,
Garfield Tan00f511d2019-06-12 16:55:40 -0700708 /*pointerCount*/ 2, pointerProperties, pointerCoords);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -0800709 ASSERT_EQ(InputEventInjectionResult::FAILED,
Prabir Pradhan4df80f52022-04-05 18:33:16 +0000710 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
711 InputEventInjectionSync::NONE, 0ms, 0))
Michael Wrightd02c5b62014-02-10 15:10:22 -0800712 << "Should reject motion events with duplicate pointer ids.";
713}
714
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800715/* Test InputDispatcher for notifyConfigurationChanged and notifySwitch events */
716
717TEST_F(InputDispatcherTest, NotifyConfigurationChanged_CallsPolicy) {
718 constexpr nsecs_t eventTime = 20;
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800719 NotifyConfigurationChangedArgs args(10 /*id*/, eventTime);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800720 mDispatcher->notifyConfigurationChanged(&args);
721 ASSERT_TRUE(mDispatcher->waitForIdle());
722
723 mFakePolicy->assertNotifyConfigurationChangedWasCalled(eventTime);
724}
725
726TEST_F(InputDispatcherTest, NotifySwitch_CallsPolicy) {
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800727 NotifySwitchArgs args(10 /*id*/, 20 /*eventTime*/, 0 /*policyFlags*/, 1 /*switchValues*/,
728 2 /*switchMask*/);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -0800729 mDispatcher->notifySwitch(&args);
730
731 // InputDispatcher adds POLICY_FLAG_TRUSTED because the event went through InputListener
732 args.policyFlags |= POLICY_FLAG_TRUSTED;
733 mFakePolicy->assertNotifySwitchWasCalled(args);
734}
735
Arthur Hungb92218b2018-08-14 12:00:21 +0800736// --- InputDispatcherTest SetInputWindowTest ---
Siarhei Vishniakou097c3db2020-05-06 14:18:38 -0700737static constexpr std::chrono::duration INJECT_EVENT_TIMEOUT = 500ms;
Siarhei Vishniakou1c494c52021-08-11 20:25:01 -0700738// Default input dispatching timeout if there is no focused application or paused window
739// from which to determine an appropriate dispatching timeout.
740static const std::chrono::duration DISPATCHING_TIMEOUT = std::chrono::milliseconds(
741 android::os::IInputConstants::UNMULTIPLIED_DEFAULT_DISPATCHING_TIMEOUT_MILLIS *
742 android::base::HwTimeoutMultiplier());
Arthur Hungb92218b2018-08-14 12:00:21 +0800743
744class FakeApplicationHandle : public InputApplicationHandle {
745public:
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700746 FakeApplicationHandle() {
747 mInfo.name = "Fake Application";
748 mInfo.token = new BBinder();
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500749 mInfo.dispatchingTimeoutMillis =
750 std::chrono::duration_cast<std::chrono::milliseconds>(DISPATCHING_TIMEOUT).count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700751 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800752 virtual ~FakeApplicationHandle() {}
753
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -1000754 virtual bool updateInfo() override { return true; }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700755
Siarhei Vishniakou70622952020-07-30 11:17:23 -0500756 void setDispatchingTimeout(std::chrono::milliseconds timeout) {
757 mInfo.dispatchingTimeoutMillis = timeout.count();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700758 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800759};
760
Arthur Hung2fbf37f2018-09-13 18:16:41 +0800761class FakeInputReceiver {
Arthur Hungb92218b2018-08-14 12:00:21 +0800762public:
Garfield Tan15601662020-09-22 15:32:38 -0700763 explicit FakeInputReceiver(std::unique_ptr<InputChannel> clientChannel, const std::string name)
chaviwd1c23182019-12-20 18:44:56 -0800764 : mName(name) {
Garfield Tan15601662020-09-22 15:32:38 -0700765 mConsumer = std::make_unique<InputConsumer>(std::move(clientChannel));
chaviwd1c23182019-12-20 18:44:56 -0800766 }
767
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800768 InputEvent* consume() {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700769 InputEvent* event;
770 std::optional<uint32_t> consumeSeq = receiveEvent(&event);
771 if (!consumeSeq) {
772 return nullptr;
773 }
774 finishEvent(*consumeSeq);
775 return event;
776 }
777
778 /**
779 * Receive an event without acknowledging it.
780 * Return the sequence number that could later be used to send finished signal.
781 */
782 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Arthur Hungb92218b2018-08-14 12:00:21 +0800783 uint32_t consumeSeq;
784 InputEvent* event;
Arthur Hungb92218b2018-08-14 12:00:21 +0800785
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800786 std::chrono::time_point start = std::chrono::steady_clock::now();
787 status_t status = WOULD_BLOCK;
788 while (status == WOULD_BLOCK) {
chaviw81e2bb92019-12-18 15:03:51 -0800789 status = mConsumer->consume(&mEventFactory, true /*consumeBatches*/, -1, &consumeSeq,
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800790 &event);
791 std::chrono::duration elapsed = std::chrono::steady_clock::now() - start;
792 if (elapsed > 100ms) {
793 break;
794 }
795 }
796
797 if (status == WOULD_BLOCK) {
798 // Just means there's no event available.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700799 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800800 }
801
802 if (status != OK) {
803 ADD_FAILURE() << mName.c_str() << ": consumer consume should return OK.";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700804 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800805 }
806 if (event == nullptr) {
807 ADD_FAILURE() << "Consumed correctly, but received NULL event from consumer";
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700808 return std::nullopt;
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800809 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700810 if (outEvent != nullptr) {
811 *outEvent = event;
812 }
813 return consumeSeq;
814 }
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800815
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -0700816 /**
817 * To be used together with "receiveEvent" to complete the consumption of an event.
818 */
819 void finishEvent(uint32_t consumeSeq) {
820 const status_t status = mConsumer->sendFinishedSignal(consumeSeq, true);
821 ASSERT_EQ(OK, status) << mName.c_str() << ": consumer sendFinishedSignal should return OK.";
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800822 }
823
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000824 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
825 const status_t status = mConsumer->sendTimeline(inputEventId, timeline);
826 ASSERT_EQ(OK, status);
827 }
828
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000829 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
830 std::optional<int32_t> expectedDisplayId,
831 std::optional<int32_t> expectedFlags) {
Siarhei Vishniakou08b574f2019-11-15 18:05:52 -0800832 InputEvent* event = consume();
833
834 ASSERT_NE(nullptr, event) << mName.c_str()
835 << ": consumer should have returned non-NULL event.";
Arthur Hungb92218b2018-08-14 12:00:21 +0800836 ASSERT_EQ(expectedEventType, event->getType())
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700837 << mName.c_str() << " expected " << inputEventTypeToString(expectedEventType)
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800838 << " event, got " << inputEventTypeToString(event->getType()) << " event";
Arthur Hungb92218b2018-08-14 12:00:21 +0800839
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000840 if (expectedDisplayId.has_value()) {
841 EXPECT_EQ(expectedDisplayId, event->getDisplayId());
842 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800843
Tiger Huang8664f8c2018-10-11 19:14:35 +0800844 switch (expectedEventType) {
845 case AINPUT_EVENT_TYPE_KEY: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800846 const KeyEvent& keyEvent = static_cast<const KeyEvent&>(*event);
847 EXPECT_EQ(expectedAction, keyEvent.getAction());
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000848 if (expectedFlags.has_value()) {
849 EXPECT_EQ(expectedFlags.value(), keyEvent.getFlags());
850 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800851 break;
852 }
853 case AINPUT_EVENT_TYPE_MOTION: {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -0800854 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +0000855 assertMotionAction(expectedAction, motionEvent.getAction());
856
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +0000857 if (expectedFlags.has_value()) {
858 EXPECT_EQ(expectedFlags.value(), motionEvent.getFlags());
859 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800860 break;
861 }
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100862 case AINPUT_EVENT_TYPE_FOCUS: {
863 FAIL() << "Use 'consumeFocusEvent' for FOCUS events";
864 }
Prabir Pradhan99987712020-11-10 18:43:05 -0800865 case AINPUT_EVENT_TYPE_CAPTURE: {
866 FAIL() << "Use 'consumeCaptureEvent' for CAPTURE events";
867 }
Antonio Kantekf16f2832021-09-28 04:39:20 +0000868 case AINPUT_EVENT_TYPE_TOUCH_MODE: {
869 FAIL() << "Use 'consumeTouchModeEvent' for TOUCH_MODE events";
870 }
arthurhungb89ccb02020-12-30 16:19:01 +0800871 case AINPUT_EVENT_TYPE_DRAG: {
872 FAIL() << "Use 'consumeDragEvent' for DRAG events";
873 }
Tiger Huang8664f8c2018-10-11 19:14:35 +0800874 default: {
875 FAIL() << mName.c_str() << ": invalid event type: " << expectedEventType;
876 }
877 }
Arthur Hungb92218b2018-08-14 12:00:21 +0800878 }
879
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100880 void consumeFocusEvent(bool hasFocus, bool inTouchMode) {
881 InputEvent* event = consume();
882 ASSERT_NE(nullptr, event) << mName.c_str()
883 << ": consumer should have returned non-NULL event.";
884 ASSERT_EQ(AINPUT_EVENT_TYPE_FOCUS, event->getType())
885 << "Got " << inputEventTypeToString(event->getType())
886 << " event instead of FOCUS event";
887
888 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
889 << mName.c_str() << ": event displayId should always be NONE.";
890
891 FocusEvent* focusEvent = static_cast<FocusEvent*>(event);
892 EXPECT_EQ(hasFocus, focusEvent->getHasFocus());
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +0100893 }
894
Prabir Pradhan99987712020-11-10 18:43:05 -0800895 void consumeCaptureEvent(bool hasCapture) {
896 const InputEvent* event = consume();
897 ASSERT_NE(nullptr, event) << mName.c_str()
898 << ": consumer should have returned non-NULL event.";
899 ASSERT_EQ(AINPUT_EVENT_TYPE_CAPTURE, event->getType())
900 << "Got " << inputEventTypeToString(event->getType())
901 << " event instead of CAPTURE event";
902
903 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
904 << mName.c_str() << ": event displayId should always be NONE.";
905
906 const auto& captureEvent = static_cast<const CaptureEvent&>(*event);
907 EXPECT_EQ(hasCapture, captureEvent.getPointerCaptureEnabled());
908 }
909
arthurhungb89ccb02020-12-30 16:19:01 +0800910 void consumeDragEvent(bool isExiting, float x, float y) {
911 const InputEvent* event = consume();
912 ASSERT_NE(nullptr, event) << mName.c_str()
913 << ": consumer should have returned non-NULL event.";
914 ASSERT_EQ(AINPUT_EVENT_TYPE_DRAG, event->getType())
915 << "Got " << inputEventTypeToString(event->getType())
916 << " event instead of DRAG event";
917
918 EXPECT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
919 << mName.c_str() << ": event displayId should always be NONE.";
920
921 const auto& dragEvent = static_cast<const DragEvent&>(*event);
922 EXPECT_EQ(isExiting, dragEvent.isExiting());
923 EXPECT_EQ(x, dragEvent.getX());
924 EXPECT_EQ(y, dragEvent.getY());
925 }
926
Antonio Kantekf16f2832021-09-28 04:39:20 +0000927 void consumeTouchModeEvent(bool inTouchMode) {
928 const InputEvent* event = consume();
929 ASSERT_NE(nullptr, event) << mName.c_str()
930 << ": consumer should have returned non-NULL event.";
931 ASSERT_EQ(AINPUT_EVENT_TYPE_TOUCH_MODE, event->getType())
932 << "Got " << inputEventTypeToString(event->getType())
933 << " event instead of TOUCH_MODE event";
934
935 ASSERT_EQ(ADISPLAY_ID_NONE, event->getDisplayId())
936 << mName.c_str() << ": event displayId should always be NONE.";
937 const auto& touchModeEvent = static_cast<const TouchModeEvent&>(*event);
938 EXPECT_EQ(inTouchMode, touchModeEvent.isInTouchMode());
939 }
940
chaviwd1c23182019-12-20 18:44:56 -0800941 void assertNoEvents() {
942 InputEvent* event = consume();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700943 if (event == nullptr) {
944 return;
945 }
946 if (event->getType() == AINPUT_EVENT_TYPE_KEY) {
947 KeyEvent& keyEvent = static_cast<KeyEvent&>(*event);
948 ADD_FAILURE() << "Received key event "
949 << KeyEvent::actionToString(keyEvent.getAction());
950 } else if (event->getType() == AINPUT_EVENT_TYPE_MOTION) {
951 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
952 ADD_FAILURE() << "Received motion event "
953 << MotionEvent::actionToString(motionEvent.getAction());
954 } else if (event->getType() == AINPUT_EVENT_TYPE_FOCUS) {
955 FocusEvent& focusEvent = static_cast<FocusEvent&>(*event);
956 ADD_FAILURE() << "Received focus event, hasFocus = "
957 << (focusEvent.getHasFocus() ? "true" : "false");
Prabir Pradhan99987712020-11-10 18:43:05 -0800958 } else if (event->getType() == AINPUT_EVENT_TYPE_CAPTURE) {
959 const auto& captureEvent = static_cast<CaptureEvent&>(*event);
960 ADD_FAILURE() << "Received capture event, pointerCaptureEnabled = "
961 << (captureEvent.getPointerCaptureEnabled() ? "true" : "false");
Antonio Kantekf16f2832021-09-28 04:39:20 +0000962 } else if (event->getType() == AINPUT_EVENT_TYPE_TOUCH_MODE) {
963 const auto& touchModeEvent = static_cast<TouchModeEvent&>(*event);
964 ADD_FAILURE() << "Received touch mode event, inTouchMode = "
965 << (touchModeEvent.isInTouchMode() ? "true" : "false");
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -0700966 }
967 FAIL() << mName.c_str()
968 << ": should not have received any events, so consume() should return NULL";
chaviwd1c23182019-12-20 18:44:56 -0800969 }
970
971 sp<IBinder> getToken() { return mConsumer->getChannel()->getConnectionToken(); }
972
Prabir Pradhan07e05b62021-11-19 03:57:24 -0800973 int getChannelFd() { return mConsumer->getChannel()->getFd().get(); }
974
chaviwd1c23182019-12-20 18:44:56 -0800975protected:
976 std::unique_ptr<InputConsumer> mConsumer;
977 PreallocatedInputEventFactory mEventFactory;
978
979 std::string mName;
980};
981
chaviw3277faf2021-05-19 16:45:23 -0500982class FakeWindowHandle : public WindowInfoHandle {
chaviwd1c23182019-12-20 18:44:56 -0800983public:
984 static const int32_t WIDTH = 600;
985 static const int32_t HEIGHT = 800;
chaviwd1c23182019-12-20 18:44:56 -0800986
Chris Yea209fde2020-07-22 13:54:51 -0700987 FakeWindowHandle(const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700988 const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500989 int32_t displayId, std::optional<sp<IBinder>> token = std::nullopt)
chaviwd1c23182019-12-20 18:44:56 -0800990 : mName(name) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -0500991 if (token == std::nullopt) {
Garfield Tan15601662020-09-22 15:32:38 -0700992 base::Result<std::unique_ptr<InputChannel>> channel =
993 dispatcher->createInputChannel(name);
994 token = (*channel)->getConnectionToken();
995 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
chaviwd1c23182019-12-20 18:44:56 -0800996 }
997
998 inputApplicationHandle->updateInfo();
999 mInfo.applicationInfo = *inputApplicationHandle->getInfo();
1000
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001001 mInfo.token = *token;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001002 mInfo.id = sId++;
chaviwd1c23182019-12-20 18:44:56 -08001003 mInfo.name = name;
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001004 mInfo.dispatchingTimeout = DISPATCHING_TIMEOUT;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001005 mInfo.alpha = 1.0;
chaviwd1c23182019-12-20 18:44:56 -08001006 mInfo.frameLeft = 0;
1007 mInfo.frameTop = 0;
1008 mInfo.frameRight = WIDTH;
1009 mInfo.frameBottom = HEIGHT;
chaviw1ff3d1e2020-07-01 15:53:47 -07001010 mInfo.transform.set(0, 0);
chaviwd1c23182019-12-20 18:44:56 -08001011 mInfo.globalScaleFactor = 1.0;
1012 mInfo.touchableRegion.clear();
1013 mInfo.addTouchableRegion(Rect(0, 0, WIDTH, HEIGHT));
Prabir Pradhan4df80f52022-04-05 18:33:16 +00001014 mInfo.ownerPid = INJECTOR_PID;
1015 mInfo.ownerUid = INJECTOR_UID;
chaviwd1c23182019-12-20 18:44:56 -08001016 mInfo.displayId = displayId;
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001017 mInfo.inputConfig = WindowInfo::InputConfig::DEFAULT;
chaviwd1c23182019-12-20 18:44:56 -08001018 }
1019
Arthur Hungabbb9d82021-09-01 14:52:30 +00001020 sp<FakeWindowHandle> clone(
1021 const std::shared_ptr<InputApplicationHandle>& inputApplicationHandle,
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001022 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId) {
Arthur Hungabbb9d82021-09-01 14:52:30 +00001023 sp<FakeWindowHandle> handle =
1024 new FakeWindowHandle(inputApplicationHandle, dispatcher, mInfo.name + "(Mirror)",
1025 displayId, mInfo.token);
1026 return handle;
1027 }
1028
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001029 void setTouchable(bool touchable) {
1030 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_TOUCHABLE, !touchable);
1031 }
chaviwd1c23182019-12-20 18:44:56 -08001032
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001033 void setFocusable(bool focusable) {
1034 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_FOCUSABLE, !focusable);
1035 }
1036
1037 void setVisible(bool visible) {
1038 mInfo.setInputConfig(WindowInfo::InputConfig::NOT_VISIBLE, !visible);
1039 }
Vishnu Nair958da932020-08-21 17:12:37 -07001040
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001041 void setDispatchingTimeout(std::chrono::nanoseconds timeout) {
Siarhei Vishniakouc1ae5562020-06-30 14:22:57 -05001042 mInfo.dispatchingTimeout = timeout;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001043 }
1044
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001045 void setPaused(bool paused) {
1046 mInfo.setInputConfig(WindowInfo::InputConfig::PAUSE_DISPATCHING, paused);
1047 }
1048
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001049 void setPreventSplitting(bool preventSplitting) {
1050 mInfo.setInputConfig(WindowInfo::InputConfig::PREVENT_SPLITTING, preventSplitting);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001051 }
1052
1053 void setSlippery(bool slippery) {
1054 mInfo.setInputConfig(WindowInfo::InputConfig::SLIPPERY, slippery);
1055 }
1056
1057 void setWatchOutsideTouch(bool watchOutside) {
1058 mInfo.setInputConfig(WindowInfo::InputConfig::WATCH_OUTSIDE_TOUCH, watchOutside);
1059 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001060
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001061 void setSpy(bool spy) { mInfo.setInputConfig(WindowInfo::InputConfig::SPY, spy); }
1062
1063 void setInterceptsStylus(bool interceptsStylus) {
1064 mInfo.setInputConfig(WindowInfo::InputConfig::INTERCEPTS_STYLUS, interceptsStylus);
1065 }
1066
1067 void setDropInput(bool dropInput) {
1068 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT, dropInput);
1069 }
1070
1071 void setDropInputIfObscured(bool dropInputIfObscured) {
1072 mInfo.setInputConfig(WindowInfo::InputConfig::DROP_INPUT_IF_OBSCURED, dropInputIfObscured);
1073 }
1074
1075 void setNoInputChannel(bool noInputChannel) {
1076 mInfo.setInputConfig(WindowInfo::InputConfig::NO_INPUT_CHANNEL, noInputChannel);
1077 }
1078
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001079 void setAlpha(float alpha) { mInfo.alpha = alpha; }
1080
chaviw3277faf2021-05-19 16:45:23 -05001081 void setTouchOcclusionMode(TouchOcclusionMode mode) { mInfo.touchOcclusionMode = mode; }
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001082
Bernardo Rufino7393d172021-02-26 13:56:11 +00001083 void setApplicationToken(sp<IBinder> token) { mInfo.applicationInfo.token = token; }
1084
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001085 void setFrame(const Rect& frame, const ui::Transform& displayTransform = ui::Transform()) {
chaviwd1c23182019-12-20 18:44:56 -08001086 mInfo.frameLeft = frame.left;
1087 mInfo.frameTop = frame.top;
1088 mInfo.frameRight = frame.right;
1089 mInfo.frameBottom = frame.bottom;
1090 mInfo.touchableRegion.clear();
1091 mInfo.addTouchableRegion(frame);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001092
1093 const Rect logicalDisplayFrame = displayTransform.transform(frame);
1094 ui::Transform translate;
1095 translate.set(-logicalDisplayFrame.left, -logicalDisplayFrame.top);
1096 mInfo.transform = translate * displayTransform;
chaviwd1c23182019-12-20 18:44:56 -08001097 }
1098
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001099 void setTouchableRegion(const Region& region) { mInfo.touchableRegion = region; }
1100
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001101 void setIsWallpaper(bool isWallpaper) {
1102 mInfo.setInputConfig(WindowInfo::InputConfig::IS_WALLPAPER, isWallpaper);
1103 }
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001104
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001105 void setDupTouchToWallpaper(bool hasWallpaper) {
1106 mInfo.setInputConfig(WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER, hasWallpaper);
1107 }
chaviwd1c23182019-12-20 18:44:56 -08001108
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001109 void setTrustedOverlay(bool trustedOverlay) {
1110 mInfo.setInputConfig(WindowInfo::InputConfig::TRUSTED_OVERLAY, trustedOverlay);
1111 }
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001112
chaviw9eaa22c2020-07-01 16:21:27 -07001113 void setWindowTransform(float dsdx, float dtdx, float dtdy, float dsdy) {
1114 mInfo.transform.set(dsdx, dtdx, dtdy, dsdy);
1115 }
1116
1117 void setWindowScale(float xScale, float yScale) { setWindowTransform(xScale, 0, 0, yScale); }
chaviwaf87b3e2019-10-01 16:59:28 -07001118
yunho.shinf4a80b82020-11-16 21:13:57 +09001119 void setWindowOffset(float offsetX, float offsetY) { mInfo.transform.set(offsetX, offsetY); }
1120
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001121 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1122 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN, expectedDisplayId,
1123 expectedFlags);
1124 }
1125
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001126 void consumeKeyUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
1127 consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, expectedDisplayId, expectedFlags);
1128 }
1129
Svet Ganov5d3bc372020-01-26 23:11:07 -08001130 void consumeMotionCancel(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001131 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001132 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, expectedDisplayId,
1133 expectedFlags);
1134 }
1135
1136 void consumeMotionMove(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001137 int32_t expectedFlags = 0) {
Svet Ganov5d3bc372020-01-26 23:11:07 -08001138 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, expectedDisplayId,
1139 expectedFlags);
1140 }
1141
1142 void consumeMotionDown(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001143 int32_t expectedFlags = 0) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001144 consumeAnyMotionDown(expectedDisplayId, expectedFlags);
1145 }
1146
1147 void consumeAnyMotionDown(std::optional<int32_t> expectedDisplayId = std::nullopt,
1148 std::optional<int32_t> expectedFlags = std::nullopt) {
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001149 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN, expectedDisplayId,
1150 expectedFlags);
1151 }
1152
Svet Ganov5d3bc372020-01-26 23:11:07 -08001153 void consumeMotionPointerDown(int32_t pointerIdx,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001154 int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1155 int32_t expectedFlags = 0) {
1156 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
1157 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001158 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1159 }
1160
1161 void consumeMotionPointerUp(int32_t pointerIdx, int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001162 int32_t expectedFlags = 0) {
1163 int32_t action = AMOTION_EVENT_ACTION_POINTER_UP |
1164 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08001165 consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, expectedDisplayId, expectedFlags);
1166 }
1167
1168 void consumeMotionUp(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001169 int32_t expectedFlags = 0) {
Michael Wright3a240c42019-12-10 20:53:41 +00001170 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP, expectedDisplayId,
1171 expectedFlags);
1172 }
1173
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05001174 void consumeMotionOutside(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1175 int32_t expectedFlags = 0) {
1176 consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE, expectedDisplayId,
1177 expectedFlags);
1178 }
1179
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08001180 void consumeMotionOutsideWithZeroedCoords(int32_t expectedDisplayId = ADISPLAY_ID_DEFAULT,
1181 int32_t expectedFlags = 0) {
1182 InputEvent* event = consume();
1183 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType());
1184 const MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
1185 EXPECT_EQ(AMOTION_EVENT_ACTION_OUTSIDE, motionEvent.getActionMasked());
1186 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getX());
1187 EXPECT_EQ(0.f, motionEvent.getRawPointerCoords(0)->getY());
1188 }
1189
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001190 void consumeFocusEvent(bool hasFocus, bool inTouchMode = true) {
1191 ASSERT_NE(mInputReceiver, nullptr)
1192 << "Cannot consume events from a window with no receiver";
1193 mInputReceiver->consumeFocusEvent(hasFocus, inTouchMode);
1194 }
1195
Prabir Pradhan99987712020-11-10 18:43:05 -08001196 void consumeCaptureEvent(bool hasCapture) {
1197 ASSERT_NE(mInputReceiver, nullptr)
1198 << "Cannot consume events from a window with no receiver";
1199 mInputReceiver->consumeCaptureEvent(hasCapture);
1200 }
1201
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00001202 void consumeEvent(int32_t expectedEventType, int32_t expectedAction,
1203 std::optional<int32_t> expectedDisplayId,
1204 std::optional<int32_t> expectedFlags) {
chaviwd1c23182019-12-20 18:44:56 -08001205 ASSERT_NE(mInputReceiver, nullptr) << "Invalid consume event on window with no receiver";
1206 mInputReceiver->consumeEvent(expectedEventType, expectedAction, expectedDisplayId,
1207 expectedFlags);
1208 }
1209
arthurhungb89ccb02020-12-30 16:19:01 +08001210 void consumeDragEvent(bool isExiting, float x, float y) {
1211 mInputReceiver->consumeDragEvent(isExiting, x, y);
1212 }
1213
Antonio Kantekf16f2832021-09-28 04:39:20 +00001214 void consumeTouchModeEvent(bool inTouchMode) {
1215 ASSERT_NE(mInputReceiver, nullptr)
1216 << "Cannot consume events from a window with no receiver";
1217 mInputReceiver->consumeTouchModeEvent(inTouchMode);
1218 }
1219
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001220 std::optional<uint32_t> receiveEvent(InputEvent** outEvent = nullptr) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001221 if (mInputReceiver == nullptr) {
1222 ADD_FAILURE() << "Invalid receive event on window with no receiver";
1223 return std::nullopt;
1224 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001225 return mInputReceiver->receiveEvent(outEvent);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001226 }
1227
1228 void finishEvent(uint32_t sequenceNum) {
1229 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1230 mInputReceiver->finishEvent(sequenceNum);
1231 }
1232
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001233 void sendTimeline(int32_t inputEventId, std::array<nsecs_t, GraphicsTimeline::SIZE> timeline) {
1234 ASSERT_NE(mInputReceiver, nullptr) << "Invalid receive event on window with no receiver";
1235 mInputReceiver->sendTimeline(inputEventId, timeline);
1236 }
1237
chaviwaf87b3e2019-10-01 16:59:28 -07001238 InputEvent* consume() {
1239 if (mInputReceiver == nullptr) {
1240 return nullptr;
1241 }
1242 return mInputReceiver->consume();
1243 }
1244
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00001245 MotionEvent* consumeMotion() {
1246 InputEvent* event = consume();
1247 if (event == nullptr) {
1248 ADD_FAILURE() << "Consume failed : no event";
1249 return nullptr;
1250 }
1251 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
1252 ADD_FAILURE() << "Instead of motion event, got "
1253 << inputEventTypeToString(event->getType());
1254 return nullptr;
1255 }
1256 return static_cast<MotionEvent*>(event);
1257 }
1258
Arthur Hungb92218b2018-08-14 12:00:21 +08001259 void assertNoEvents() {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001260 if (mInputReceiver == nullptr &&
Prabir Pradhan51e7db02022-02-07 06:02:57 -08001261 mInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL)) {
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05001262 return; // Can't receive events if the window does not have input channel
1263 }
1264 ASSERT_NE(nullptr, mInputReceiver)
1265 << "Window without InputReceiver must specify feature NO_INPUT_CHANNEL";
chaviwd1c23182019-12-20 18:44:56 -08001266 mInputReceiver->assertNoEvents();
Arthur Hungb92218b2018-08-14 12:00:21 +08001267 }
1268
chaviwaf87b3e2019-10-01 16:59:28 -07001269 sp<IBinder> getToken() { return mInfo.token; }
1270
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001271 const std::string& getName() { return mName; }
1272
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001273 void setOwnerInfo(int32_t ownerPid, int32_t ownerUid) {
1274 mInfo.ownerPid = ownerPid;
1275 mInfo.ownerUid = ownerUid;
1276 }
1277
Prabir Pradhanedd96402022-02-15 01:46:16 -08001278 int32_t getPid() const { return mInfo.ownerPid; }
1279
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001280 void destroyReceiver() { mInputReceiver = nullptr; }
1281
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001282 int getChannelFd() { return mInputReceiver->getChannelFd(); }
1283
chaviwd1c23182019-12-20 18:44:56 -08001284private:
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01001285 const std::string mName;
chaviwd1c23182019-12-20 18:44:56 -08001286 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001287 static std::atomic<int32_t> sId; // each window gets a unique id, like in surfaceflinger
Arthur Hung2fbf37f2018-09-13 18:16:41 +08001288};
1289
Siarhei Vishniakou540dbae2020-05-05 18:17:17 -07001290std::atomic<int32_t> FakeWindowHandle::sId{1};
1291
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001292static InputEventInjectionResult injectKey(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001293 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t repeatCount,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001294 int32_t displayId = ADISPLAY_ID_NONE,
1295 InputEventInjectionSync syncMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001296 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan4df80f52022-04-05 18:33:16 +00001297 bool allowKeyRepeat = true) {
Arthur Hungb92218b2018-08-14 12:00:21 +08001298 KeyEvent event;
1299 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1300
1301 // Define a valid key down event.
Garfield Tanfbe732e2020-01-24 11:26:14 -08001302 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, displayId,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001303 INVALID_HMAC, action, /* flags */ 0, AKEYCODE_A, KEY_A, AMETA_NONE,
1304 repeatCount, currentTime, currentTime);
Arthur Hungb92218b2018-08-14 12:00:21 +08001305
Prabir Pradhan4df80f52022-04-05 18:33:16 +00001306 int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001307 if (!allowKeyRepeat) {
1308 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
1309 }
Arthur Hungb92218b2018-08-14 12:00:21 +08001310 // Inject event until dispatch out.
Prabir Pradhan4df80f52022-04-05 18:33:16 +00001311 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, syncMode,
1312 injectionTimeout, policyFlags);
Arthur Hungb92218b2018-08-14 12:00:21 +08001313}
1314
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001315static InputEventInjectionResult injectKeyDown(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001316 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001317 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId);
1318}
1319
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001320// Inject a down event that has key repeat disabled. This allows InputDispatcher to idle without
1321// sending a subsequent key up. When key repeat is enabled, the dispatcher cannot idle because it
1322// has to be woken up to process the repeating key.
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001323static InputEventInjectionResult injectKeyDownNoRepeat(
1324 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t displayId = ADISPLAY_ID_NONE) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08001325 return injectKey(dispatcher, AKEY_EVENT_ACTION_DOWN, /* repeatCount */ 0, displayId,
1326 InputEventInjectionSync::WAIT_FOR_RESULT, INJECT_EVENT_TIMEOUT,
1327 /* allowKeyRepeat */ false);
1328}
1329
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001330static InputEventInjectionResult injectKeyUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001331 int32_t displayId = ADISPLAY_ID_NONE) {
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001332 return injectKey(dispatcher, AKEY_EVENT_ACTION_UP, /* repeatCount */ 0, displayId);
1333}
1334
Garfield Tandf26e862020-07-01 20:18:19 -07001335class PointerBuilder {
1336public:
1337 PointerBuilder(int32_t id, int32_t toolType) {
1338 mProperties.clear();
1339 mProperties.id = id;
1340 mProperties.toolType = toolType;
1341 mCoords.clear();
1342 }
1343
1344 PointerBuilder& x(float x) { return axis(AMOTION_EVENT_AXIS_X, x); }
1345
1346 PointerBuilder& y(float y) { return axis(AMOTION_EVENT_AXIS_Y, y); }
1347
1348 PointerBuilder& axis(int32_t axis, float value) {
1349 mCoords.setAxisValue(axis, value);
1350 return *this;
1351 }
1352
1353 PointerProperties buildProperties() const { return mProperties; }
1354
1355 PointerCoords buildCoords() const { return mCoords; }
1356
1357private:
1358 PointerProperties mProperties;
1359 PointerCoords mCoords;
1360};
1361
1362class MotionEventBuilder {
1363public:
1364 MotionEventBuilder(int32_t action, int32_t source) {
1365 mAction = action;
1366 mSource = source;
1367 mEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
1368 }
1369
1370 MotionEventBuilder& eventTime(nsecs_t eventTime) {
1371 mEventTime = eventTime;
1372 return *this;
1373 }
1374
1375 MotionEventBuilder& displayId(int32_t displayId) {
1376 mDisplayId = displayId;
1377 return *this;
1378 }
1379
1380 MotionEventBuilder& actionButton(int32_t actionButton) {
1381 mActionButton = actionButton;
1382 return *this;
1383 }
1384
arthurhung6d4bed92021-03-17 11:59:33 +08001385 MotionEventBuilder& buttonState(int32_t buttonState) {
1386 mButtonState = buttonState;
Garfield Tandf26e862020-07-01 20:18:19 -07001387 return *this;
1388 }
1389
1390 MotionEventBuilder& rawXCursorPosition(float rawXCursorPosition) {
1391 mRawXCursorPosition = rawXCursorPosition;
1392 return *this;
1393 }
1394
1395 MotionEventBuilder& rawYCursorPosition(float rawYCursorPosition) {
1396 mRawYCursorPosition = rawYCursorPosition;
1397 return *this;
1398 }
1399
1400 MotionEventBuilder& pointer(PointerBuilder pointer) {
1401 mPointers.push_back(pointer);
1402 return *this;
1403 }
1404
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001405 MotionEventBuilder& addFlag(uint32_t flags) {
1406 mFlags |= flags;
1407 return *this;
1408 }
1409
Garfield Tandf26e862020-07-01 20:18:19 -07001410 MotionEvent build() {
1411 std::vector<PointerProperties> pointerProperties;
1412 std::vector<PointerCoords> pointerCoords;
1413 for (const PointerBuilder& pointer : mPointers) {
1414 pointerProperties.push_back(pointer.buildProperties());
1415 pointerCoords.push_back(pointer.buildCoords());
1416 }
1417
1418 // Set mouse cursor position for the most common cases to avoid boilerplate.
1419 if (mSource == AINPUT_SOURCE_MOUSE &&
1420 !MotionEvent::isValidCursorPosition(mRawXCursorPosition, mRawYCursorPosition) &&
1421 mPointers.size() == 1) {
1422 mRawXCursorPosition = pointerCoords[0].getX();
1423 mRawYCursorPosition = pointerCoords[0].getY();
1424 }
1425
1426 MotionEvent event;
chaviw9eaa22c2020-07-01 16:21:27 -07001427 ui::Transform identityTransform;
Garfield Tandf26e862020-07-01 20:18:19 -07001428 event.initialize(InputEvent::nextId(), DEVICE_ID, mSource, mDisplayId, INVALID_HMAC,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001429 mAction, mActionButton, mFlags, /* edgeFlags */ 0, AMETA_NONE,
chaviw9eaa22c2020-07-01 16:21:27 -07001430 mButtonState, MotionClassification::NONE, identityTransform,
1431 /* xPrecision */ 0, /* yPrecision */ 0, mRawXCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001432 mRawYCursorPosition, identityTransform, mEventTime, mEventTime,
1433 mPointers.size(), pointerProperties.data(), pointerCoords.data());
Garfield Tandf26e862020-07-01 20:18:19 -07001434
1435 return event;
1436 }
1437
1438private:
1439 int32_t mAction;
1440 int32_t mSource;
1441 nsecs_t mEventTime;
1442 int32_t mDisplayId{ADISPLAY_ID_DEFAULT};
1443 int32_t mActionButton{0};
1444 int32_t mButtonState{0};
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08001445 int32_t mFlags{0};
Garfield Tandf26e862020-07-01 20:18:19 -07001446 float mRawXCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1447 float mRawYCursorPosition{AMOTION_EVENT_INVALID_CURSOR_POSITION};
1448
1449 std::vector<PointerBuilder> mPointers;
1450};
1451
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001452static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001453 const std::unique_ptr<InputDispatcher>& dispatcher, const MotionEvent& event,
Garfield Tandf26e862020-07-01 20:18:19 -07001454 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Prabir Pradhan4df80f52022-04-05 18:33:16 +00001455 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT) {
1456 return dispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID, injectionMode,
1457 injectionTimeout,
1458 POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER);
Garfield Tandf26e862020-07-01 20:18:19 -07001459}
1460
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001461static InputEventInjectionResult injectMotionEvent(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001462 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t action, int32_t source,
Prabir Pradhan07e05b62021-11-19 03:57:24 -08001463 int32_t displayId, const PointF& position = {100, 200},
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001464 const PointF& cursorPosition = {AMOTION_EVENT_INVALID_CURSOR_POSITION,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07001465 AMOTION_EVENT_INVALID_CURSOR_POSITION},
1466 std::chrono::milliseconds injectionTimeout = INJECT_EVENT_TIMEOUT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001467 InputEventInjectionSync injectionMode = InputEventInjectionSync::WAIT_FOR_RESULT,
Prabir Pradhan4df80f52022-04-05 18:33:16 +00001468 nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC)) {
Garfield Tandf26e862020-07-01 20:18:19 -07001469 MotionEvent event = MotionEventBuilder(action, source)
1470 .displayId(displayId)
1471 .eventTime(eventTime)
1472 .rawXCursorPosition(cursorPosition.x)
1473 .rawYCursorPosition(cursorPosition.y)
1474 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1475 .x(position.x)
1476 .y(position.y))
1477 .build();
Arthur Hungb92218b2018-08-14 12:00:21 +08001478
1479 // Inject event until dispatch out.
Prabir Pradhan4df80f52022-04-05 18:33:16 +00001480 return injectMotionEvent(dispatcher, event, injectionTimeout, injectionMode);
Arthur Hungb92218b2018-08-14 12:00:21 +08001481}
1482
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001483static InputEventInjectionResult injectMotionDown(
1484 const std::unique_ptr<InputDispatcher>& dispatcher, int32_t source, int32_t displayId,
1485 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001486 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_DOWN, source, displayId, location);
Garfield Tan00f511d2019-06-12 16:55:40 -07001487}
1488
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001489static InputEventInjectionResult injectMotionUp(const std::unique_ptr<InputDispatcher>& dispatcher,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001490 int32_t source, int32_t displayId,
1491 const PointF& location = {100, 200}) {
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07001492 return injectMotionEvent(dispatcher, AMOTION_EVENT_ACTION_UP, source, displayId, location);
Michael Wright3a240c42019-12-10 20:53:41 +00001493}
1494
Jackal Guof9696682018-10-05 12:23:23 +08001495static NotifyKeyArgs generateKeyArgs(int32_t action, int32_t displayId = ADISPLAY_ID_NONE) {
1496 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1497 // Define a valid key event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001498 NotifyKeyArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, AINPUT_SOURCE_KEYBOARD,
1499 displayId, POLICY_FLAG_PASS_TO_USER, action, /* flags */ 0, AKEYCODE_A,
1500 KEY_A, AMETA_NONE, currentTime);
Jackal Guof9696682018-10-05 12:23:23 +08001501
1502 return args;
1503}
1504
chaviwd1c23182019-12-20 18:44:56 -08001505static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId,
1506 const std::vector<PointF>& points) {
1507 size_t pointerCount = points.size();
chaviwaf87b3e2019-10-01 16:59:28 -07001508 if (action == AMOTION_EVENT_ACTION_DOWN || action == AMOTION_EVENT_ACTION_UP) {
1509 EXPECT_EQ(1U, pointerCount) << "Actions DOWN and UP can only contain a single pointer";
1510 }
1511
chaviwd1c23182019-12-20 18:44:56 -08001512 PointerProperties pointerProperties[pointerCount];
1513 PointerCoords pointerCoords[pointerCount];
Jackal Guof9696682018-10-05 12:23:23 +08001514
chaviwd1c23182019-12-20 18:44:56 -08001515 for (size_t i = 0; i < pointerCount; i++) {
1516 pointerProperties[i].clear();
1517 pointerProperties[i].id = i;
1518 pointerProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Jackal Guof9696682018-10-05 12:23:23 +08001519
chaviwd1c23182019-12-20 18:44:56 -08001520 pointerCoords[i].clear();
1521 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X, points[i].x);
1522 pointerCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y, points[i].y);
1523 }
Jackal Guof9696682018-10-05 12:23:23 +08001524
1525 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
1526 // Define a valid motion event.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001527 NotifyMotionArgs args(/* id */ 0, currentTime, 0 /*readTime*/, DEVICE_ID, source, displayId,
Garfield Tan00f511d2019-06-12 16:55:40 -07001528 POLICY_FLAG_PASS_TO_USER, action, /* actionButton */ 0, /* flags */ 0,
1529 AMETA_NONE, /* buttonState */ 0, MotionClassification::NONE,
chaviwd1c23182019-12-20 18:44:56 -08001530 AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount, pointerProperties,
1531 pointerCoords, /* xPrecision */ 0, /* yPrecision */ 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07001532 AMOTION_EVENT_INVALID_CURSOR_POSITION,
1533 AMOTION_EVENT_INVALID_CURSOR_POSITION, currentTime, /* videoFrames */ {});
Jackal Guof9696682018-10-05 12:23:23 +08001534
1535 return args;
1536}
1537
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001538static NotifyMotionArgs generateTouchArgs(int32_t action, const std::vector<PointF>& points) {
1539 return generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN, DISPLAY_ID, points);
1540}
1541
chaviwd1c23182019-12-20 18:44:56 -08001542static NotifyMotionArgs generateMotionArgs(int32_t action, int32_t source, int32_t displayId) {
1543 return generateMotionArgs(action, source, displayId, {PointF{100, 200}});
1544}
1545
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001546static NotifyPointerCaptureChangedArgs generatePointerCaptureChangedArgs(
1547 const PointerCaptureRequest& request) {
1548 return NotifyPointerCaptureChangedArgs(/* id */ 0, systemTime(SYSTEM_TIME_MONOTONIC), request);
Prabir Pradhan99987712020-11-10 18:43:05 -08001549}
1550
Siarhei Vishniakou7aa3e942021-11-18 09:49:11 -08001551/**
1552 * When a window unexpectedly disposes of its input channel, policy should be notified about the
1553 * broken channel.
1554 */
1555TEST_F(InputDispatcherTest, WhenInputChannelBreaks_PolicyIsNotified) {
1556 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1557 sp<FakeWindowHandle> window =
1558 new FakeWindowHandle(application, mDispatcher, "Window that breaks its input channel",
1559 ADISPLAY_ID_DEFAULT);
1560
1561 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1562
1563 // Window closes its channel, but the window remains.
1564 window->destroyReceiver();
1565 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(window->getInfo()->token);
1566}
1567
Arthur Hungb92218b2018-08-14 12:00:21 +08001568TEST_F(InputDispatcherTest, SetInputWindow_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001569 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001570 sp<FakeWindowHandle> window =
1571 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001572
Arthur Hung72d8dc32020-03-28 00:48:39 +00001573 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001574 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1575 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1576 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001577
1578 // Window should receive motion event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001579 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001580}
1581
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07001582TEST_F(InputDispatcherTest, WhenDisplayNotSpecified_InjectMotionToDefaultDisplay) {
1583 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1584 sp<FakeWindowHandle> window =
1585 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1586
1587 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1588 // Inject a MotionEvent to an unknown display.
1589 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1590 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_NONE))
1591 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1592
1593 // Window should receive motion event.
1594 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1595}
1596
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001597/**
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001598 * Calling setInputWindows once should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001599 * This test serves as a sanity check for the next test, where setInputWindows is
1600 * called twice.
1601 */
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08001602TEST_F(InputDispatcherTest, SetInputWindowOnceWithSingleTouchWindow) {
Chris Yea209fde2020-07-22 13:54:51 -07001603 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001604 sp<FakeWindowHandle> window =
1605 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1606 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001607
1608 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001609 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001610 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1611 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001612 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001613
1614 // Window should receive motion event.
1615 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1616}
1617
1618/**
1619 * Calling setInputWindows twice, with the same info, should not cause any issues.
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001620 */
1621TEST_F(InputDispatcherTest, SetInputWindowTwice_SingleWindowTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001622 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001623 sp<FakeWindowHandle> window =
1624 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
1625 window->setFrame(Rect(0, 0, 100, 100));
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001626
1627 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
1628 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001629 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001630 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1631 {50, 50}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001632 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07001633
1634 // Window should receive motion event.
1635 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1636}
1637
Arthur Hungb92218b2018-08-14 12:00:21 +08001638// The foreground window should receive the first touch down event.
1639TEST_F(InputDispatcherTest, SetInputWindow_MultiWindowsTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07001640 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10001641 sp<FakeWindowHandle> windowTop =
1642 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
1643 sp<FakeWindowHandle> windowSecond =
1644 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001645
Arthur Hung72d8dc32020-03-28 00:48:39 +00001646 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001647 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1648 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
1649 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08001650
1651 // Top window should receive the touch down event. Second window should not receive anything.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08001652 windowTop->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08001653 windowSecond->assertNoEvents();
1654}
1655
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001656/**
1657 * Two windows: A top window, and a wallpaper behind the window.
1658 * Touch goes to the top window, and then top window disappears. Ensure that wallpaper window
1659 * gets ACTION_CANCEL.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001660 * 1. foregroundWindow <-- dup touch to wallpaper
1661 * 2. wallpaperWindow <-- is wallpaper
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001662 */
1663TEST_F(InputDispatcherTest, WhenForegroundWindowDisappears_WallpaperTouchIsCanceled) {
1664 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1665 sp<FakeWindowHandle> foregroundWindow =
1666 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001667 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001668 sp<FakeWindowHandle> wallpaperWindow =
1669 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001670 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001671 constexpr int expectedWallpaperFlags =
1672 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1673
1674 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1675 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1676 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1677 {100, 200}))
1678 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1679
1680 // Both foreground window and its wallpaper should receive the touch down
1681 foregroundWindow->consumeMotionDown();
1682 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1683
1684 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1685 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1686 ADISPLAY_ID_DEFAULT, {110, 200}))
1687 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1688
1689 foregroundWindow->consumeMotionMove();
1690 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1691
1692 // Now the foreground window goes away, but the wallpaper stays
1693 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1694 foregroundWindow->consumeMotionCancel();
1695 // Since the "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1696 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1697}
1698
1699/**
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001700 * Same test as WhenForegroundWindowDisappears_WallpaperTouchIsCanceled above,
1701 * with the following differences:
1702 * After ACTION_DOWN, Wallpaper window hangs up its channel, which forces the dispatcher to
1703 * clean up the connection.
1704 * This later may crash dispatcher during ACTION_CANCEL synthesis, if the dispatcher is not careful.
1705 * Ensure that there's no crash in the dispatcher.
1706 */
1707TEST_F(InputDispatcherTest, WhenWallpaperDisappears_NoCrash) {
1708 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1709 sp<FakeWindowHandle> foregroundWindow =
1710 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001711 foregroundWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001712 sp<FakeWindowHandle> wallpaperWindow =
1713 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001714 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakou2b030972021-11-18 10:01:27 -08001715 constexpr int expectedWallpaperFlags =
1716 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1717
1718 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
1719 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1720 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1721 {100, 200}))
1722 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1723
1724 // Both foreground window and its wallpaper should receive the touch down
1725 foregroundWindow->consumeMotionDown();
1726 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1727
1728 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1729 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
1730 ADISPLAY_ID_DEFAULT, {110, 200}))
1731 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1732
1733 foregroundWindow->consumeMotionMove();
1734 wallpaperWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1735
1736 // Wallpaper closes its channel, but the window remains.
1737 wallpaperWindow->destroyReceiver();
1738 mFakePolicy->assertNotifyInputChannelBrokenWasCalled(wallpaperWindow->getInfo()->token);
1739
1740 // Now the foreground window goes away, but the wallpaper stays, even though its channel
1741 // is no longer valid.
1742 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wallpaperWindow}}});
1743 foregroundWindow->consumeMotionCancel();
1744}
1745
1746/**
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001747 * A single window that receives touch (on top), and a wallpaper window underneath it.
1748 * The top window gets a multitouch gesture.
1749 * Ensure that wallpaper gets the same gesture.
1750 */
1751TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
1752 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1753 sp<FakeWindowHandle> window =
1754 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001755 window->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001756
1757 sp<FakeWindowHandle> wallpaperWindow =
1758 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001759 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001760 constexpr int expectedWallpaperFlags =
1761 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1762
1763 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
1764
1765 // Touch down on top window
1766 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1767 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1768 {100, 100}))
1769 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1770
1771 // Both top window and its wallpaper should receive the touch down
1772 window->consumeMotionDown();
1773 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1774
1775 // Second finger down on the top window
1776 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001777 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001778 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1779 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1780 .x(100)
1781 .y(100))
1782 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1783 .x(150)
1784 .y(150))
1785 .build();
1786 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1787 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1788 InputEventInjectionSync::WAIT_FOR_RESULT))
1789 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1790
1791 window->consumeMotionPointerDown(1 /* pointerIndex */);
1792 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1793 expectedWallpaperFlags);
1794 window->assertNoEvents();
1795 wallpaperWindow->assertNoEvents();
1796}
1797
1798/**
1799 * Two windows: a window on the left and window on the right.
1800 * A third window, wallpaper, is behind both windows, and spans both top windows.
1801 * The first touch down goes to the left window. A second pointer touches down on the right window.
1802 * The touch is split, so both left and right windows should receive ACTION_DOWN.
1803 * The wallpaper will get the full event, so it should receive ACTION_DOWN followed by
1804 * ACTION_POINTER_DOWN(1).
1805 */
1806TEST_F(InputDispatcherTest, TwoWindows_SplitWallpaperTouch) {
1807 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1808 sp<FakeWindowHandle> leftWindow =
1809 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1810 leftWindow->setFrame(Rect(0, 0, 200, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001811 leftWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001812
1813 sp<FakeWindowHandle> rightWindow =
1814 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1815 rightWindow->setFrame(Rect(200, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001816 rightWindow->setDupTouchToWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001817
1818 sp<FakeWindowHandle> wallpaperWindow =
1819 new FakeWindowHandle(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
1820 wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08001821 wallpaperWindow->setIsWallpaper(true);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001822 constexpr int expectedWallpaperFlags =
1823 AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
1824
1825 mDispatcher->setInputWindows(
1826 {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
1827
1828 // Touch down on left window
1829 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1830 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
1831 {100, 100}))
1832 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1833
1834 // Both foreground window and its wallpaper should receive the touch down
1835 leftWindow->consumeMotionDown();
1836 wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1837
1838 // Second finger down on the right window
1839 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001840 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Siarhei Vishniakouca205502021-07-16 21:31:58 +00001841 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1842 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1843 .x(100)
1844 .y(100))
1845 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1846 .x(300)
1847 .y(100))
1848 .build();
1849 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1850 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
1851 InputEventInjectionSync::WAIT_FOR_RESULT))
1852 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
1853
1854 leftWindow->consumeMotionMove();
1855 // Since the touch is split, right window gets ACTION_DOWN
1856 rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1857 wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
1858 expectedWallpaperFlags);
1859
1860 // Now, leftWindow, which received the first finger, disappears.
1861 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {rightWindow, wallpaperWindow}}});
1862 leftWindow->consumeMotionCancel();
1863 // Since a "parent" window of the wallpaper is gone, wallpaper should receive cancel, too.
1864 wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
1865
1866 // The pointer that's still down on the right window moves, and goes to the right window only.
1867 // As far as the dispatcher's concerned though, both pointers are still present.
1868 const MotionEvent secondFingerMoveEvent =
1869 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN)
1870 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
1871 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
1872 .x(100)
1873 .y(100))
1874 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
1875 .x(310)
1876 .y(110))
1877 .build();
1878 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
1879 injectMotionEvent(mDispatcher, secondFingerMoveEvent, INJECT_EVENT_TIMEOUT,
1880 InputEventInjectionSync::WAIT_FOR_RESULT));
1881 rightWindow->consumeMotionMove();
1882
1883 leftWindow->assertNoEvents();
1884 rightWindow->assertNoEvents();
1885 wallpaperWindow->assertNoEvents();
1886}
1887
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08001888/**
1889 * On the display, have a single window, and also an area where there's no window.
1890 * First pointer touches the "no window" area of the screen. Second pointer touches the window.
1891 * Make sure that the window receives the second pointer, and first pointer is simply ignored.
1892 */
1893TEST_F(InputDispatcherTest, SplitWorksWhenEmptyAreaIsTouched) {
1894 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1895 sp<FakeWindowHandle> window =
1896 new FakeWindowHandle(application, mDispatcher, "Window", DISPLAY_ID);
1897
1898 mDispatcher->setInputWindows({{DISPLAY_ID, {window}}});
1899 NotifyMotionArgs args;
1900
1901 // Touch down on the empty space
1902 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{-1, -1}})));
1903
1904 mDispatcher->waitForIdle();
1905 window->assertNoEvents();
1906
1907 // Now touch down on the window with another pointer
1908 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{-1, -1}, {10, 10}})));
1909 mDispatcher->waitForIdle();
1910 window->consumeMotionDown();
1911}
1912
1913/**
1914 * Same test as above, but instead of touching the empty space, the first touch goes to
1915 * non-touchable window.
1916 */
1917TEST_F(InputDispatcherTest, SplitWorksWhenNonTouchableWindowIsTouched) {
1918 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
1919 sp<FakeWindowHandle> window1 =
1920 new FakeWindowHandle(application, mDispatcher, "Window1", DISPLAY_ID);
1921 window1->setTouchableRegion(Region{{0, 0, 100, 100}});
1922 window1->setTouchable(false);
1923 sp<FakeWindowHandle> window2 =
1924 new FakeWindowHandle(application, mDispatcher, "Window2", DISPLAY_ID);
1925 window2->setTouchableRegion(Region{{100, 0, 200, 100}});
1926
1927 mDispatcher->setInputWindows({{DISPLAY_ID, {window1, window2}}});
1928
1929 NotifyMotionArgs args;
1930 // Touch down on the non-touchable window
1931 mDispatcher->notifyMotion(&(args = generateTouchArgs(AMOTION_EVENT_ACTION_DOWN, {{50, 50}})));
1932
1933 mDispatcher->waitForIdle();
1934 window1->assertNoEvents();
1935 window2->assertNoEvents();
1936
1937 // Now touch down on the window with another pointer
1938 mDispatcher->notifyMotion(&(args = generateTouchArgs(POINTER_1_DOWN, {{50, 50}, {150, 50}})));
1939 mDispatcher->waitForIdle();
1940 window2->consumeMotionDown();
1941}
1942
Garfield Tandf26e862020-07-01 20:18:19 -07001943TEST_F(InputDispatcherTest, HoverMoveEnterMouseClickAndHoverMoveExit) {
Chris Yea209fde2020-07-22 13:54:51 -07001944 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07001945 sp<FakeWindowHandle> windowLeft =
1946 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
1947 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001948 sp<FakeWindowHandle> windowRight =
1949 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
1950 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07001951
1952 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
1953
1954 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
1955
1956 // Start cursor position in right window so that we can move the cursor to left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001957 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001958 injectMotionEvent(mDispatcher,
1959 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1960 AINPUT_SOURCE_MOUSE)
1961 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1962 .x(900)
1963 .y(400))
1964 .build()));
1965 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1966 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1967 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1968 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1969
1970 // Move cursor into left window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001971 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001972 injectMotionEvent(mDispatcher,
1973 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
1974 AINPUT_SOURCE_MOUSE)
1975 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1976 .x(300)
1977 .y(400))
1978 .build()));
1979 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
1980 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1981 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
1982 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1983 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
1984 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
1985
1986 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001987 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001988 injectMotionEvent(mDispatcher,
1989 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
1990 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
1991 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
1992 .x(300)
1993 .y(400))
1994 .build()));
1995 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
1996
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08001997 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07001998 injectMotionEvent(mDispatcher,
1999 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2000 AINPUT_SOURCE_MOUSE)
2001 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2002 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2003 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2004 .x(300)
2005 .y(400))
2006 .build()));
2007 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2008 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2009
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002010 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002011 injectMotionEvent(mDispatcher,
2012 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2013 AINPUT_SOURCE_MOUSE)
2014 .buttonState(0)
2015 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2016 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2017 .x(300)
2018 .y(400))
2019 .build()));
2020 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2021 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2022
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002023 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002024 injectMotionEvent(mDispatcher,
2025 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2026 .buttonState(0)
2027 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2028 .x(300)
2029 .y(400))
2030 .build()));
2031 windowLeft->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2032
2033 // Move mouse cursor back to right window
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002034 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002035 injectMotionEvent(mDispatcher,
2036 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_MOVE,
2037 AINPUT_SOURCE_MOUSE)
2038 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2039 .x(900)
2040 .y(400))
2041 .build()));
2042 windowLeft->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2043 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2044 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2045 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2046 windowRight->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_MOVE,
2047 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2048}
2049
2050// This test is different from the test above that HOVER_ENTER and HOVER_EXIT events are injected
2051// directly in this test.
2052TEST_F(InputDispatcherTest, HoverEnterMouseClickAndHoverExit) {
Chris Yea209fde2020-07-22 13:54:51 -07002053 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tandf26e862020-07-01 20:18:19 -07002054 sp<FakeWindowHandle> window =
2055 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2056 window->setFrame(Rect(0, 0, 1200, 800));
Garfield Tandf26e862020-07-01 20:18:19 -07002057
2058 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2059
2060 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2061
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002062 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002063 injectMotionEvent(mDispatcher,
2064 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_ENTER,
2065 AINPUT_SOURCE_MOUSE)
2066 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2067 .x(300)
2068 .y(400))
2069 .build()));
2070 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_ENTER,
2071 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2072
2073 // Inject a series of mouse events for a mouse click
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002074 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002075 injectMotionEvent(mDispatcher,
2076 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
2077 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2078 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2079 .x(300)
2080 .y(400))
2081 .build()));
2082 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2083
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002084 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002085 injectMotionEvent(mDispatcher,
2086 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_PRESS,
2087 AINPUT_SOURCE_MOUSE)
2088 .buttonState(AMOTION_EVENT_BUTTON_PRIMARY)
2089 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2090 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2091 .x(300)
2092 .y(400))
2093 .build()));
2094 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2095 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2096
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002097 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002098 injectMotionEvent(mDispatcher,
2099 MotionEventBuilder(AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2100 AINPUT_SOURCE_MOUSE)
2101 .buttonState(0)
2102 .actionButton(AMOTION_EVENT_BUTTON_PRIMARY)
2103 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2104 .x(300)
2105 .y(400))
2106 .build()));
2107 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2108 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2109
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002110 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002111 injectMotionEvent(mDispatcher,
2112 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_MOUSE)
2113 .buttonState(0)
2114 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2115 .x(300)
2116 .y(400))
2117 .build()));
2118 window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
2119
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002120 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tandf26e862020-07-01 20:18:19 -07002121 injectMotionEvent(mDispatcher,
2122 MotionEventBuilder(AMOTION_EVENT_ACTION_HOVER_EXIT,
2123 AINPUT_SOURCE_MOUSE)
2124 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_MOUSE)
2125 .x(300)
2126 .y(400))
2127 .build()));
2128 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_HOVER_EXIT,
2129 ADISPLAY_ID_DEFAULT, 0 /* expectedFlag */);
2130}
2131
Garfield Tan00f511d2019-06-12 16:55:40 -07002132TEST_F(InputDispatcherTest, DispatchMouseEventsUnderCursor) {
Chris Yea209fde2020-07-22 13:54:51 -07002133 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Garfield Tan00f511d2019-06-12 16:55:40 -07002134
2135 sp<FakeWindowHandle> windowLeft =
2136 new FakeWindowHandle(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
2137 windowLeft->setFrame(Rect(0, 0, 600, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002138 sp<FakeWindowHandle> windowRight =
2139 new FakeWindowHandle(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
2140 windowRight->setFrame(Rect(600, 0, 1200, 800));
Garfield Tan00f511d2019-06-12 16:55:40 -07002141
2142 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
2143
Arthur Hung72d8dc32020-03-28 00:48:39 +00002144 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
Garfield Tan00f511d2019-06-12 16:55:40 -07002145
2146 // Inject an event with coordinate in the area of right window, with mouse cursor in the area of
2147 // left window. This event should be dispatched to the left window.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08002148 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Garfield Tan00f511d2019-06-12 16:55:40 -07002149 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07002150 ADISPLAY_ID_DEFAULT, {610, 400}, {599, 400}));
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08002151 windowLeft->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Garfield Tan00f511d2019-06-12 16:55:40 -07002152 windowRight->assertNoEvents();
2153}
2154
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002155TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsKeyStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002156 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002157 sp<FakeWindowHandle> window =
2158 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Vishnu Nair47074b82020-08-14 11:54:47 -07002159 window->setFocusable(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002160
Arthur Hung72d8dc32020-03-28 00:48:39 +00002161 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002162 setFocusedWindow(window);
2163
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002164 window->consumeFocusEvent(true);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002165
2166 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2167 mDispatcher->notifyKey(&keyArgs);
2168
2169 // Window should receive key down event.
2170 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2171
2172 // When device reset happens, that key stream should be terminated with FLAG_CANCELED
2173 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002174 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002175 mDispatcher->notifyDeviceReset(&args);
2176 window->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
2177 AKEY_EVENT_FLAG_CANCELED);
2178}
2179
2180TEST_F(InputDispatcherTest, NotifyDeviceReset_CancelsMotionStream) {
Chris Yea209fde2020-07-22 13:54:51 -07002181 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002182 sp<FakeWindowHandle> window =
2183 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2184
Arthur Hung72d8dc32020-03-28 00:48:39 +00002185 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002186
2187 NotifyMotionArgs motionArgs =
2188 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2189 ADISPLAY_ID_DEFAULT);
2190 mDispatcher->notifyMotion(&motionArgs);
2191
2192 // Window should receive motion down event.
2193 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2194
2195 // When device reset happens, that motion stream should be terminated with ACTION_CANCEL
2196 // on the app side.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002197 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08002198 mDispatcher->notifyDeviceReset(&args);
2199 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
2200 0 /*expectedFlags*/);
2201}
2202
Arthur Hung2ee6d0b2022-03-03 20:19:38 +08002203TEST_F(InputDispatcherTest, InterceptKeyByPolicy) {
2204 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2205 sp<FakeWindowHandle> window =
2206 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2207 window->setFocusable(true);
2208
2209 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2210 setFocusedWindow(window);
2211
2212 window->consumeFocusEvent(true);
2213
2214 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2215 const std::chrono::milliseconds interceptKeyTimeout = 50ms;
2216 const nsecs_t injectTime = keyArgs.eventTime;
2217 mFakePolicy->setInterceptKeyTimeout(interceptKeyTimeout);
2218 mDispatcher->notifyKey(&keyArgs);
2219 // The dispatching time should be always greater than or equal to intercept key timeout.
2220 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2221 ASSERT_TRUE((systemTime(SYSTEM_TIME_MONOTONIC) - injectTime) >=
2222 std::chrono::nanoseconds(interceptKeyTimeout).count());
2223}
2224
2225TEST_F(InputDispatcherTest, InterceptKeyIfKeyUp) {
2226 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2227 sp<FakeWindowHandle> window =
2228 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2229 window->setFocusable(true);
2230
2231 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2232 setFocusedWindow(window);
2233
2234 window->consumeFocusEvent(true);
2235
2236 NotifyKeyArgs keyDown = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2237 NotifyKeyArgs keyUp = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
2238 mFakePolicy->setInterceptKeyTimeout(150ms);
2239 mDispatcher->notifyKey(&keyDown);
2240 mDispatcher->notifyKey(&keyUp);
2241
2242 // Window should receive key event immediately when same key up.
2243 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2244 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
2245}
2246
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002247/**
2248 * Ensure the correct coordinate spaces are used by InputDispatcher.
2249 *
2250 * InputDispatcher works in the display space, so its coordinate system is relative to the display
2251 * panel. Windows get events in the window space, and get raw coordinates in the logical display
2252 * space.
2253 */
2254class InputDispatcherDisplayProjectionTest : public InputDispatcherTest {
2255public:
2256 void SetUp() override {
2257 InputDispatcherTest::SetUp();
2258 mDisplayInfos.clear();
2259 mWindowInfos.clear();
2260 }
2261
2262 void addDisplayInfo(int displayId, const ui::Transform& transform) {
2263 gui::DisplayInfo info;
2264 info.displayId = displayId;
2265 info.transform = transform;
2266 mDisplayInfos.push_back(std::move(info));
2267 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2268 }
2269
2270 void addWindow(const sp<WindowInfoHandle>& windowHandle) {
2271 mWindowInfos.push_back(*windowHandle->getInfo());
2272 mDispatcher->onWindowInfosChanged(mWindowInfos, mDisplayInfos);
2273 }
2274
2275 // Set up a test scenario where the display has a scaled projection and there are two windows
2276 // on the display.
2277 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupScaledDisplayScenario() {
2278 // The display has a projection that has a scale factor of 2 and 4 in the x and y directions
2279 // respectively.
2280 ui::Transform displayTransform;
2281 displayTransform.set(2, 0, 0, 4);
2282 addDisplayInfo(ADISPLAY_ID_DEFAULT, displayTransform);
2283
2284 std::shared_ptr<FakeApplicationHandle> application =
2285 std::make_shared<FakeApplicationHandle>();
2286
2287 // Add two windows to the display. Their frames are represented in the display space.
2288 sp<FakeWindowHandle> firstWindow =
2289 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002290 firstWindow->setFrame(Rect(0, 0, 100, 200), displayTransform);
2291 addWindow(firstWindow);
2292
2293 sp<FakeWindowHandle> secondWindow =
2294 new FakeWindowHandle(application, mDispatcher, "Second Window",
2295 ADISPLAY_ID_DEFAULT);
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002296 secondWindow->setFrame(Rect(100, 200, 200, 400), displayTransform);
2297 addWindow(secondWindow);
2298 return {std::move(firstWindow), std::move(secondWindow)};
2299 }
2300
2301private:
2302 std::vector<gui::DisplayInfo> mDisplayInfos;
2303 std::vector<gui::WindowInfo> mWindowInfos;
2304};
2305
2306TEST_F(InputDispatcherDisplayProjectionTest, HitTestsInDisplaySpace) {
2307 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2308 // Send down to the first window. The point is represented in the display space. The point is
2309 // selected so that if the hit test was done with the transform applied to it, then it would
2310 // end up in the incorrect window.
2311 NotifyMotionArgs downMotionArgs =
2312 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2313 ADISPLAY_ID_DEFAULT, {PointF{75, 55}});
2314 mDispatcher->notifyMotion(&downMotionArgs);
2315
2316 firstWindow->consumeMotionDown();
2317 secondWindow->assertNoEvents();
2318}
2319
2320// Ensure that when a MotionEvent is injected through the InputDispatcher::injectInputEvent() API,
2321// the event should be treated as being in the logical display space.
2322TEST_F(InputDispatcherDisplayProjectionTest, InjectionInLogicalDisplaySpace) {
2323 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2324 // Send down to the first window. The point is represented in the logical display space. The
2325 // point is selected so that if the hit test was done in logical display space, then it would
2326 // end up in the incorrect window.
2327 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2328 PointF{75 * 2, 55 * 4});
2329
2330 firstWindow->consumeMotionDown();
2331 secondWindow->assertNoEvents();
2332}
2333
Prabir Pradhandaa2f142021-12-10 09:30:08 +00002334// Ensure that when a MotionEvent that has a custom transform is injected, the post-transformed
2335// event should be treated as being in the logical display space.
2336TEST_F(InputDispatcherDisplayProjectionTest, InjectionWithTransformInLogicalDisplaySpace) {
2337 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2338
2339 const std::array<float, 9> matrix = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0.0, 0.0, 1.0};
2340 ui::Transform injectedEventTransform;
2341 injectedEventTransform.set(matrix);
2342 const vec2 expectedPoint{75, 55}; // The injected point in the logical display space.
2343 const vec2 untransformedPoint = injectedEventTransform.inverse().transform(expectedPoint);
2344
2345 MotionEvent event = MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
2346 .displayId(ADISPLAY_ID_DEFAULT)
2347 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
2348 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
2349 .x(untransformedPoint.x)
2350 .y(untransformedPoint.y))
2351 .build();
2352 event.transform(matrix);
2353
2354 injectMotionEvent(mDispatcher, event, INJECT_EVENT_TIMEOUT,
2355 InputEventInjectionSync::WAIT_FOR_RESULT);
2356
2357 firstWindow->consumeMotionDown();
2358 secondWindow->assertNoEvents();
2359}
2360
Prabir Pradhanc44ce4d2021-10-05 05:26:29 -07002361TEST_F(InputDispatcherDisplayProjectionTest, WindowGetsEventsInCorrectCoordinateSpace) {
2362 auto [firstWindow, secondWindow] = setupScaledDisplayScenario();
2363
2364 // Send down to the second window.
2365 NotifyMotionArgs downMotionArgs =
2366 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2367 ADISPLAY_ID_DEFAULT, {PointF{150, 220}});
2368 mDispatcher->notifyMotion(&downMotionArgs);
2369
2370 firstWindow->assertNoEvents();
2371 const MotionEvent* event = secondWindow->consumeMotion();
2372 EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, event->getAction());
2373
2374 // Ensure that the events from the "getRaw" API are in logical display coordinates.
2375 EXPECT_EQ(300, event->getRawX(0));
2376 EXPECT_EQ(880, event->getRawY(0));
2377
2378 // Ensure that the x and y values are in the window's coordinate space.
2379 // The left-top of the second window is at (100, 200) in display space, which is (200, 800) in
2380 // the logical display space. This will be the origin of the window space.
2381 EXPECT_EQ(100, event->getX(0));
2382 EXPECT_EQ(80, event->getY(0));
2383}
2384
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002385using TransferFunction = std::function<bool(const std::unique_ptr<InputDispatcher>& dispatcher,
2386 sp<IBinder>, sp<IBinder>)>;
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002387
2388class TransferTouchFixture : public InputDispatcherTest,
2389 public ::testing::WithParamInterface<TransferFunction> {};
2390
2391TEST_P(TransferTouchFixture, TransferTouch_OnePointer) {
Chris Yea209fde2020-07-22 13:54:51 -07002392 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002393
2394 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002395 sp<FakeWindowHandle> firstWindow =
2396 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2397 sp<FakeWindowHandle> secondWindow =
2398 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002399
2400 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002401 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002402
2403 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002404 NotifyMotionArgs downMotionArgs =
2405 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2406 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002407 mDispatcher->notifyMotion(&downMotionArgs);
2408 // Only the first window should get the down event
2409 firstWindow->consumeMotionDown();
2410 secondWindow->assertNoEvents();
2411
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002412 // Transfer touch to the second window
2413 TransferFunction f = GetParam();
2414 const bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2415 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002416 // The first window gets cancel and the second gets down
2417 firstWindow->consumeMotionCancel();
2418 secondWindow->consumeMotionDown();
2419
2420 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002421 NotifyMotionArgs upMotionArgs =
2422 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2423 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002424 mDispatcher->notifyMotion(&upMotionArgs);
2425 // The first window gets no events and the second gets up
2426 firstWindow->assertNoEvents();
2427 secondWindow->consumeMotionUp();
2428}
2429
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002430TEST_P(TransferTouchFixture, TransferTouch_TwoPointersNonSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002431 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002432
2433 PointF touchPoint = {10, 10};
2434
2435 // Create a couple of windows
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002436 sp<FakeWindowHandle> firstWindow =
2437 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002438 firstWindow->setPreventSplitting(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002439 sp<FakeWindowHandle> secondWindow =
2440 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08002441 secondWindow->setPreventSplitting(true);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002442
2443 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002444 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002445
2446 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002447 NotifyMotionArgs downMotionArgs =
2448 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2449 ADISPLAY_ID_DEFAULT, {touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002450 mDispatcher->notifyMotion(&downMotionArgs);
2451 // Only the first window should get the down event
2452 firstWindow->consumeMotionDown();
2453 secondWindow->assertNoEvents();
2454
2455 // Send pointer down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002456 NotifyMotionArgs pointerDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002457 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002458 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002459 mDispatcher->notifyMotion(&pointerDownMotionArgs);
2460 // Only the first window should get the pointer down event
2461 firstWindow->consumeMotionPointerDown(1);
2462 secondWindow->assertNoEvents();
2463
2464 // Transfer touch focus to the second window
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002465 TransferFunction f = GetParam();
2466 bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
2467 ASSERT_TRUE(success);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002468 // The first window gets cancel and the second gets down and pointer down
2469 firstWindow->consumeMotionCancel();
2470 secondWindow->consumeMotionDown();
2471 secondWindow->consumeMotionPointerDown(1);
2472
2473 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002474 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002475 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002476 {touchPoint, touchPoint});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002477 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2478 // The first window gets nothing and the second gets pointer up
2479 firstWindow->assertNoEvents();
2480 secondWindow->consumeMotionPointerUp(1);
2481
2482 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002483 NotifyMotionArgs upMotionArgs =
2484 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2485 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002486 mDispatcher->notifyMotion(&upMotionArgs);
2487 // The first window gets nothing and the second gets up
2488 firstWindow->assertNoEvents();
2489 secondWindow->consumeMotionUp();
2490}
2491
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002492// For the cases of single pointer touch and two pointers non-split touch, the api's
2493// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
2494// for the case where there are multiple pointers split across several windows.
2495INSTANTIATE_TEST_SUITE_P(TransferFunctionTests, TransferTouchFixture,
2496 ::testing::Values(
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002497 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2498 sp<IBinder> /*ignored*/, sp<IBinder> destChannelToken) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002499 return dispatcher->transferTouch(destChannelToken);
2500 },
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002501 [&](const std::unique_ptr<InputDispatcher>& dispatcher,
2502 sp<IBinder> from, sp<IBinder> to) {
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002503 return dispatcher->transferTouchFocus(from, to,
2504 false /*isDragAndDrop*/);
2505 }));
2506
Svet Ganov5d3bc372020-01-26 23:11:07 -08002507TEST_F(InputDispatcherTest, TransferTouchFocus_TwoPointersSplitTouch) {
Chris Yea209fde2020-07-22 13:54:51 -07002508 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Svet Ganov5d3bc372020-01-26 23:11:07 -08002509
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002510 sp<FakeWindowHandle> firstWindow =
2511 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002512 firstWindow->setFrame(Rect(0, 0, 600, 400));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002513
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002514 sp<FakeWindowHandle> secondWindow =
2515 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002516 secondWindow->setFrame(Rect(0, 400, 600, 800));
Svet Ganov5d3bc372020-01-26 23:11:07 -08002517
2518 // Add the windows to the dispatcher
Arthur Hung72d8dc32020-03-28 00:48:39 +00002519 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002520
2521 PointF pointInFirst = {300, 200};
2522 PointF pointInSecond = {300, 600};
2523
2524 // Send down to the first window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002525 NotifyMotionArgs firstDownMotionArgs =
2526 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2527 ADISPLAY_ID_DEFAULT, {pointInFirst});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002528 mDispatcher->notifyMotion(&firstDownMotionArgs);
2529 // Only the first window should get the down event
2530 firstWindow->consumeMotionDown();
2531 secondWindow->assertNoEvents();
2532
2533 // Send down to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002534 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002535 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002536 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002537 mDispatcher->notifyMotion(&secondDownMotionArgs);
2538 // The first window gets a move and the second a down
2539 firstWindow->consumeMotionMove();
2540 secondWindow->consumeMotionDown();
2541
2542 // Transfer touch focus to the second window
2543 mDispatcher->transferTouchFocus(firstWindow->getToken(), secondWindow->getToken());
2544 // The first window gets cancel and the new gets pointer down (it already saw down)
2545 firstWindow->consumeMotionCancel();
2546 secondWindow->consumeMotionPointerDown(1);
2547
2548 // Send pointer up to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002549 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002550 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002551 {pointInFirst, pointInSecond});
Svet Ganov5d3bc372020-01-26 23:11:07 -08002552 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2553 // The first window gets nothing and the second gets pointer up
2554 firstWindow->assertNoEvents();
2555 secondWindow->consumeMotionPointerUp(1);
2556
2557 // Send up event to the second window
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10002558 NotifyMotionArgs upMotionArgs =
2559 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2560 ADISPLAY_ID_DEFAULT);
Svet Ganov5d3bc372020-01-26 23:11:07 -08002561 mDispatcher->notifyMotion(&upMotionArgs);
2562 // The first window gets nothing and the second gets up
2563 firstWindow->assertNoEvents();
2564 secondWindow->consumeMotionUp();
2565}
2566
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002567// Same as TransferTouchFocus_TwoPointersSplitTouch, but using 'transferTouch' api.
2568// Unlike 'transferTouchFocus', calling 'transferTouch' when there are two windows receiving
2569// touch is not supported, so the touch should continue on those windows and the transferred-to
2570// window should get nothing.
2571TEST_F(InputDispatcherTest, TransferTouch_TwoPointersSplitTouch) {
2572 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2573
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002574 sp<FakeWindowHandle> firstWindow =
2575 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2576 firstWindow->setFrame(Rect(0, 0, 600, 400));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002577
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002578 sp<FakeWindowHandle> secondWindow =
2579 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2580 secondWindow->setFrame(Rect(0, 400, 600, 800));
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002581
2582 // Add the windows to the dispatcher
2583 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2584
2585 PointF pointInFirst = {300, 200};
2586 PointF pointInSecond = {300, 600};
2587
2588 // Send down to the first window
2589 NotifyMotionArgs firstDownMotionArgs =
2590 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2591 ADISPLAY_ID_DEFAULT, {pointInFirst});
2592 mDispatcher->notifyMotion(&firstDownMotionArgs);
2593 // Only the first window should get the down event
2594 firstWindow->consumeMotionDown();
2595 secondWindow->assertNoEvents();
2596
2597 // Send down to the second window
2598 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002599 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002600 {pointInFirst, pointInSecond});
2601 mDispatcher->notifyMotion(&secondDownMotionArgs);
2602 // The first window gets a move and the second a down
2603 firstWindow->consumeMotionMove();
2604 secondWindow->consumeMotionDown();
2605
2606 // Transfer touch focus to the second window
2607 const bool transferred = mDispatcher->transferTouch(secondWindow->getToken());
2608 // The 'transferTouch' call should not succeed, because there are 2 touched windows
2609 ASSERT_FALSE(transferred);
2610 firstWindow->assertNoEvents();
2611 secondWindow->assertNoEvents();
2612
2613 // The rest of the dispatch should proceed as normal
2614 // Send pointer up to the second window
2615 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002616 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoud0c6bc82021-03-13 03:14:52 +00002617 {pointInFirst, pointInSecond});
2618 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2619 // The first window gets MOVE and the second gets pointer up
2620 firstWindow->consumeMotionMove();
2621 secondWindow->consumeMotionUp();
2622
2623 // Send up event to the first window
2624 NotifyMotionArgs upMotionArgs =
2625 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2626 ADISPLAY_ID_DEFAULT);
2627 mDispatcher->notifyMotion(&upMotionArgs);
2628 // The first window gets nothing and the second gets up
2629 firstWindow->consumeMotionUp();
2630 secondWindow->assertNoEvents();
2631}
2632
Arthur Hungabbb9d82021-09-01 14:52:30 +00002633// This case will create two windows and one mirrored window on the default display and mirror
2634// two windows on the second display. It will test if 'transferTouchFocus' works fine if we put
2635// the windows info of second display before default display.
2636TEST_F(InputDispatcherTest, TransferTouchFocus_CloneSurface) {
2637 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2638 sp<FakeWindowHandle> firstWindowInPrimary =
2639 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2640 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002641 sp<FakeWindowHandle> secondWindowInPrimary =
2642 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2643 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002644
2645 sp<FakeWindowHandle> mirrorWindowInPrimary =
2646 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2647 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002648
2649 sp<FakeWindowHandle> firstWindowInSecondary =
2650 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2651 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002652
2653 sp<FakeWindowHandle> secondWindowInSecondary =
2654 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2655 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002656
2657 // Update window info, let it find window handle of second display first.
2658 mDispatcher->setInputWindows(
2659 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2660 {ADISPLAY_ID_DEFAULT,
2661 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2662
2663 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2664 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2665 {50, 50}))
2666 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2667
2668 // Window should receive motion event.
2669 firstWindowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2670
2671 // Transfer touch focus
2672 ASSERT_TRUE(mDispatcher->transferTouchFocus(firstWindowInPrimary->getToken(),
2673 secondWindowInPrimary->getToken()));
2674 // The first window gets cancel.
2675 firstWindowInPrimary->consumeMotionCancel();
2676 secondWindowInPrimary->consumeMotionDown();
2677
2678 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2679 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2680 ADISPLAY_ID_DEFAULT, {150, 50}))
2681 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2682 firstWindowInPrimary->assertNoEvents();
2683 secondWindowInPrimary->consumeMotionMove();
2684
2685 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2686 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2687 {150, 50}))
2688 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2689 firstWindowInPrimary->assertNoEvents();
2690 secondWindowInPrimary->consumeMotionUp();
2691}
2692
2693// Same as TransferTouchFocus_CloneSurface, but this touch on the secondary display and use
2694// 'transferTouch' api.
2695TEST_F(InputDispatcherTest, TransferTouch_CloneSurface) {
2696 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2697 sp<FakeWindowHandle> firstWindowInPrimary =
2698 new FakeWindowHandle(application, mDispatcher, "D_1_W1", ADISPLAY_ID_DEFAULT);
2699 firstWindowInPrimary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002700 sp<FakeWindowHandle> secondWindowInPrimary =
2701 new FakeWindowHandle(application, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
2702 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002703
2704 sp<FakeWindowHandle> mirrorWindowInPrimary =
2705 firstWindowInPrimary->clone(application, mDispatcher, ADISPLAY_ID_DEFAULT);
2706 mirrorWindowInPrimary->setFrame(Rect(0, 100, 100, 200));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002707
2708 sp<FakeWindowHandle> firstWindowInSecondary =
2709 firstWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2710 firstWindowInSecondary->setFrame(Rect(0, 0, 100, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002711
2712 sp<FakeWindowHandle> secondWindowInSecondary =
2713 secondWindowInPrimary->clone(application, mDispatcher, SECOND_DISPLAY_ID);
2714 secondWindowInPrimary->setFrame(Rect(100, 0, 200, 100));
Arthur Hungabbb9d82021-09-01 14:52:30 +00002715
2716 // Update window info, let it find window handle of second display first.
2717 mDispatcher->setInputWindows(
2718 {{SECOND_DISPLAY_ID, {firstWindowInSecondary, secondWindowInSecondary}},
2719 {ADISPLAY_ID_DEFAULT,
2720 {mirrorWindowInPrimary, firstWindowInPrimary, secondWindowInPrimary}}});
2721
2722 // Touch on second display.
2723 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2724 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {50, 50}))
2725 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2726
2727 // Window should receive motion event.
2728 firstWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2729
2730 // Transfer touch focus
2731 ASSERT_TRUE(mDispatcher->transferTouch(secondWindowInSecondary->getToken()));
2732
2733 // The first window gets cancel.
2734 firstWindowInPrimary->consumeMotionCancel(SECOND_DISPLAY_ID);
2735 secondWindowInPrimary->consumeMotionDown(SECOND_DISPLAY_ID);
2736
2737 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2738 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2739 SECOND_DISPLAY_ID, {150, 50}))
2740 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2741 firstWindowInPrimary->assertNoEvents();
2742 secondWindowInPrimary->consumeMotionMove(SECOND_DISPLAY_ID);
2743
2744 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2745 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID, {150, 50}))
2746 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2747 firstWindowInPrimary->assertNoEvents();
2748 secondWindowInPrimary->consumeMotionUp(SECOND_DISPLAY_ID);
2749}
2750
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002751TEST_F(InputDispatcherTest, FocusedWindow_ReceivesFocusEventAndKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002752 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002753 sp<FakeWindowHandle> window =
2754 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2755
Vishnu Nair47074b82020-08-14 11:54:47 -07002756 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002757 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07002758 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002759
2760 window->consumeFocusEvent(true);
2761
2762 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2763 mDispatcher->notifyKey(&keyArgs);
2764
2765 // Window should receive key down event.
2766 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
2767}
2768
2769TEST_F(InputDispatcherTest, UnfocusedWindow_DoesNotReceiveFocusEventOrKeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07002770 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002771 sp<FakeWindowHandle> window =
2772 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2773
Arthur Hung72d8dc32020-03-28 00:48:39 +00002774 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002775
2776 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2777 mDispatcher->notifyKey(&keyArgs);
2778 mDispatcher->waitForIdle();
2779
2780 window->assertNoEvents();
2781}
2782
2783// If a window is touchable, but does not have focus, it should receive motion events, but not keys
2784TEST_F(InputDispatcherTest, UnfocusedWindow_ReceivesMotionsButNotKeys) {
Chris Yea209fde2020-07-22 13:54:51 -07002785 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002786 sp<FakeWindowHandle> window =
2787 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
2788
Arthur Hung72d8dc32020-03-28 00:48:39 +00002789 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01002790
2791 // Send key
2792 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
2793 mDispatcher->notifyKey(&keyArgs);
2794 // Send motion
2795 NotifyMotionArgs motionArgs =
2796 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2797 ADISPLAY_ID_DEFAULT);
2798 mDispatcher->notifyMotion(&motionArgs);
2799
2800 // Window should receive only the motion event
2801 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
2802 window->assertNoEvents(); // Key event or focus event will not be received
2803}
2804
arthurhungea3f4fc2020-12-21 23:18:53 +08002805TEST_F(InputDispatcherTest, PointerCancel_SendCancelWhenSplitTouch) {
2806 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2807
arthurhungea3f4fc2020-12-21 23:18:53 +08002808 sp<FakeWindowHandle> firstWindow =
2809 new FakeWindowHandle(application, mDispatcher, "First Window", ADISPLAY_ID_DEFAULT);
2810 firstWindow->setFrame(Rect(0, 0, 600, 400));
arthurhungea3f4fc2020-12-21 23:18:53 +08002811
arthurhungea3f4fc2020-12-21 23:18:53 +08002812 sp<FakeWindowHandle> secondWindow =
2813 new FakeWindowHandle(application, mDispatcher, "Second Window", ADISPLAY_ID_DEFAULT);
2814 secondWindow->setFrame(Rect(0, 400, 600, 800));
arthurhungea3f4fc2020-12-21 23:18:53 +08002815
2816 // Add the windows to the dispatcher
2817 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
2818
2819 PointF pointInFirst = {300, 200};
2820 PointF pointInSecond = {300, 600};
2821
2822 // Send down to the first window
2823 NotifyMotionArgs firstDownMotionArgs =
2824 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
2825 ADISPLAY_ID_DEFAULT, {pointInFirst});
2826 mDispatcher->notifyMotion(&firstDownMotionArgs);
2827 // Only the first window should get the down event
2828 firstWindow->consumeMotionDown();
2829 secondWindow->assertNoEvents();
2830
2831 // Send down to the second window
2832 NotifyMotionArgs secondDownMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002833 generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08002834 {pointInFirst, pointInSecond});
2835 mDispatcher->notifyMotion(&secondDownMotionArgs);
2836 // The first window gets a move and the second a down
2837 firstWindow->consumeMotionMove();
2838 secondWindow->consumeMotionDown();
2839
2840 // Send pointer cancel to the second window
2841 NotifyMotionArgs pointerUpMotionArgs =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08002842 generateMotionArgs(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
arthurhungea3f4fc2020-12-21 23:18:53 +08002843 {pointInFirst, pointInSecond});
2844 pointerUpMotionArgs.flags |= AMOTION_EVENT_FLAG_CANCELED;
2845 mDispatcher->notifyMotion(&pointerUpMotionArgs);
2846 // The first window gets move and the second gets cancel.
2847 firstWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2848 secondWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_CANCELED);
2849
2850 // Send up event.
2851 NotifyMotionArgs upMotionArgs =
2852 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
2853 ADISPLAY_ID_DEFAULT);
2854 mDispatcher->notifyMotion(&upMotionArgs);
2855 // The first window gets up and the second gets nothing.
2856 firstWindow->consumeMotionUp();
2857 secondWindow->assertNoEvents();
2858}
2859
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00002860TEST_F(InputDispatcherTest, SendTimeline_DoesNotCrashDispatcher) {
2861 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2862
2863 sp<FakeWindowHandle> window =
2864 new FakeWindowHandle(application, mDispatcher, "Window", ADISPLAY_ID_DEFAULT);
2865 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2866 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline;
2867 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME] = 2;
2868 graphicsTimeline[GraphicsTimeline::PRESENT_TIME] = 3;
2869
2870 window->sendTimeline(1 /*inputEventId*/, graphicsTimeline);
2871 window->assertNoEvents();
2872 mDispatcher->waitForIdle();
2873}
2874
chaviwd1c23182019-12-20 18:44:56 -08002875class FakeMonitorReceiver {
Michael Wright3a240c42019-12-10 20:53:41 +00002876public:
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002877 FakeMonitorReceiver(const std::unique_ptr<InputDispatcher>& dispatcher, const std::string name,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002878 int32_t displayId) {
Garfield Tan15601662020-09-22 15:32:38 -07002879 base::Result<std::unique_ptr<InputChannel>> channel =
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08002880 dispatcher->createInputMonitor(displayId, name, MONITOR_PID);
Garfield Tan15601662020-09-22 15:32:38 -07002881 mInputReceiver = std::make_unique<FakeInputReceiver>(std::move(*channel), name);
Michael Wright3a240c42019-12-10 20:53:41 +00002882 }
2883
chaviwd1c23182019-12-20 18:44:56 -08002884 sp<IBinder> getToken() { return mInputReceiver->getToken(); }
2885
2886 void consumeKeyDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2887 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_DOWN,
2888 expectedDisplayId, expectedFlags);
2889 }
2890
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07002891 std::optional<int32_t> receiveEvent() { return mInputReceiver->receiveEvent(); }
2892
2893 void finishEvent(uint32_t consumeSeq) { return mInputReceiver->finishEvent(consumeSeq); }
2894
chaviwd1c23182019-12-20 18:44:56 -08002895 void consumeMotionDown(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2896 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_DOWN,
2897 expectedDisplayId, expectedFlags);
2898 }
2899
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002900 void consumeMotionMove(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2901 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE,
2902 expectedDisplayId, expectedFlags);
2903 }
2904
chaviwd1c23182019-12-20 18:44:56 -08002905 void consumeMotionUp(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2906 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_UP,
2907 expectedDisplayId, expectedFlags);
2908 }
2909
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002910 void consumeMotionCancel(int32_t expectedDisplayId, int32_t expectedFlags = 0) {
2911 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
2912 expectedDisplayId, expectedFlags);
2913 }
2914
Arthur Hungfbfa5722021-11-16 02:45:54 +00002915 void consumeMotionPointerDown(int32_t pointerIdx) {
2916 int32_t action = AMOTION_EVENT_ACTION_POINTER_DOWN |
2917 (pointerIdx << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
2918 mInputReceiver->consumeEvent(AINPUT_EVENT_TYPE_MOTION, action, ADISPLAY_ID_DEFAULT,
2919 0 /*expectedFlags*/);
2920 }
2921
Evan Rosky84f07f02021-04-16 10:42:42 -07002922 MotionEvent* consumeMotion() {
2923 InputEvent* event = mInputReceiver->consume();
2924 if (!event) {
2925 ADD_FAILURE() << "No event was produced";
2926 return nullptr;
2927 }
2928 if (event->getType() != AINPUT_EVENT_TYPE_MOTION) {
2929 ADD_FAILURE() << "Received event of type " << event->getType() << " instead of motion";
2930 return nullptr;
2931 }
2932 return static_cast<MotionEvent*>(event);
2933 }
2934
chaviwd1c23182019-12-20 18:44:56 -08002935 void assertNoEvents() { mInputReceiver->assertNoEvents(); }
2936
2937private:
2938 std::unique_ptr<FakeInputReceiver> mInputReceiver;
Michael Wright3a240c42019-12-10 20:53:41 +00002939};
2940
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002941using InputDispatcherMonitorTest = InputDispatcherTest;
2942
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002943/**
2944 * Two entities that receive touch: A window, and a global monitor.
2945 * The touch goes to the window, and then the window disappears.
2946 * The monitor does not get cancel right away. But if more events come in, the touch gets canceled
2947 * for the monitor, as well.
2948 * 1. foregroundWindow
2949 * 2. monitor <-- global monitor (doesn't observe z order, receives all events)
2950 */
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002951TEST_F(InputDispatcherMonitorTest, MonitorTouchIsCanceledWhenForegroundWindowDisappears) {
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002952 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
2953 sp<FakeWindowHandle> window =
2954 new FakeWindowHandle(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
2955
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002956 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00002957
2958 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
2959 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2960 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
2961 {100, 200}))
2962 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2963
2964 // Both the foreground window and the global monitor should receive the touch down
2965 window->consumeMotionDown();
2966 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
2967
2968 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
2969 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2970 ADISPLAY_ID_DEFAULT, {110, 200}))
2971 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
2972
2973 window->consumeMotionMove();
2974 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
2975
2976 // Now the foreground window goes away
2977 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
2978 window->consumeMotionCancel();
2979 monitor.assertNoEvents(); // Global monitor does not get a cancel yet
2980
2981 // If more events come in, there will be no more foreground window to send them to. This will
2982 // cause a cancel for the monitor, as well.
2983 ASSERT_EQ(InputEventInjectionResult::FAILED,
2984 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
2985 ADISPLAY_ID_DEFAULT, {120, 200}))
2986 << "Injection should fail because the window was removed";
2987 window->assertNoEvents();
2988 // Global monitor now gets the cancel
2989 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
2990}
2991
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002992TEST_F(InputDispatcherMonitorTest, ReceivesMotionEvents) {
Chris Yea209fde2020-07-22 13:54:51 -07002993 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00002994 sp<FakeWindowHandle> window =
2995 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00002996 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00002997
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08002998 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00002999
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003000 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003001 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003002 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Michael Wright3a240c42019-12-10 20:53:41 +00003003 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003004 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003005}
3006
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003007TEST_F(InputDispatcherMonitorTest, MonitorCannotPilferPointers) {
3008 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003009
Chris Yea209fde2020-07-22 13:54:51 -07003010 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Michael Wright3a240c42019-12-10 20:53:41 +00003011 sp<FakeWindowHandle> window =
3012 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003013 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Michael Wright3a240c42019-12-10 20:53:41 +00003014
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003015 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Michael Wright3a240c42019-12-10 20:53:41 +00003016 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003017 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
chaviwd1c23182019-12-20 18:44:56 -08003018 monitor.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003019 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003020
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003021 // Pilfer pointers from the monitor.
3022 // This should not do anything and the window should continue to receive events.
3023 EXPECT_NE(OK, mDispatcher->pilferPointers(monitor.getToken()));
Michael Wright3a240c42019-12-10 20:53:41 +00003024
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003025 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003026 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3027 ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003028 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003029
3030 monitor.consumeMotionMove(ADISPLAY_ID_DEFAULT);
3031 window->consumeMotionMove(ADISPLAY_ID_DEFAULT);
Michael Wright3a240c42019-12-10 20:53:41 +00003032}
3033
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003034TEST_F(InputDispatcherMonitorTest, NoWindowTransform) {
Evan Rosky84f07f02021-04-16 10:42:42 -07003035 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3036 sp<FakeWindowHandle> window =
3037 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3038 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3039 window->setWindowOffset(20, 40);
3040 window->setWindowTransform(0, 1, -1, 0);
3041
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003042 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Evan Rosky84f07f02021-04-16 10:42:42 -07003043
3044 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3045 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3046 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3047 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3048 MotionEvent* event = monitor.consumeMotion();
3049 // Even though window has transform, gesture monitor must not.
3050 ASSERT_EQ(ui::Transform(), event->getTransform());
3051}
3052
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003053TEST_F(InputDispatcherMonitorTest, InjectionFailsWithNoWindow) {
Arthur Hungb3307ee2021-10-14 10:57:37 +00003054 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003055 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
Arthur Hungb3307ee2021-10-14 10:57:37 +00003056
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003057 ASSERT_EQ(InputEventInjectionResult::FAILED,
Arthur Hungb3307ee2021-10-14 10:57:37 +00003058 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08003059 << "Injection should fail if there is a monitor, but no touchable window";
3060 monitor.assertNoEvents();
Arthur Hungb3307ee2021-10-14 10:57:37 +00003061}
3062
chaviw81e2bb92019-12-18 15:03:51 -08003063TEST_F(InputDispatcherTest, TestMoveEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003064 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
chaviw81e2bb92019-12-18 15:03:51 -08003065 sp<FakeWindowHandle> window =
3066 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3067
Arthur Hung72d8dc32020-03-28 00:48:39 +00003068 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
chaviw81e2bb92019-12-18 15:03:51 -08003069
3070 NotifyMotionArgs motionArgs =
3071 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3072 ADISPLAY_ID_DEFAULT);
3073
3074 mDispatcher->notifyMotion(&motionArgs);
3075 // Window should receive motion down event.
3076 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3077
3078 motionArgs.action = AMOTION_EVENT_ACTION_MOVE;
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003079 motionArgs.id += 1;
chaviw81e2bb92019-12-18 15:03:51 -08003080 motionArgs.eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3081 motionArgs.pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3082 motionArgs.pointerCoords[0].getX() - 10);
3083
3084 mDispatcher->notifyMotion(&motionArgs);
3085 window->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_MOVE, ADISPLAY_ID_DEFAULT,
3086 0 /*expectedFlags*/);
3087}
3088
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003089/**
3090 * Dispatcher has touch mode enabled by default. Typically, the policy overrides that value to
3091 * the device default right away. In the test scenario, we check both the default value,
3092 * and the action of enabling / disabling.
3093 */
3094TEST_F(InputDispatcherTest, TouchModeState_IsSentToApps) {
Chris Yea209fde2020-07-22 13:54:51 -07003095 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003096 sp<FakeWindowHandle> window =
3097 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Antonio Kantekea47acb2021-12-23 12:41:25 -08003098 const WindowInfo& windowInfo = *window->getInfo();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003099
3100 // Set focused application.
3101 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003102 window->setFocusable(true);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003103
3104 SCOPED_TRACE("Check default value of touch mode");
Arthur Hung72d8dc32020-03-28 00:48:39 +00003105 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003106 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003107 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3108
3109 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003110 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003111 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003112 window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
3113
3114 SCOPED_TRACE("Disable touch mode");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003115 mDispatcher->setInTouchMode(false, windowInfo.ownerPid, windowInfo.ownerUid,
3116 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003117 window->consumeTouchModeEvent(false);
Vishnu Nair47074b82020-08-14 11:54:47 -07003118 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003119 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003120 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003121 window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
3122
3123 SCOPED_TRACE("Remove the window to trigger focus loss");
Vishnu Nair47074b82020-08-14 11:54:47 -07003124 window->setFocusable(false);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003125 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003126 window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
3127
3128 SCOPED_TRACE("Enable touch mode again");
Antonio Kantekea47acb2021-12-23 12:41:25 -08003129 mDispatcher->setInTouchMode(true, windowInfo.ownerPid, windowInfo.ownerUid,
3130 /* hasPermission */ true);
Antonio Kantekf16f2832021-09-28 04:39:20 +00003131 window->consumeTouchModeEvent(true);
Vishnu Nair47074b82020-08-14 11:54:47 -07003132 window->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003133 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003134 setFocusedWindow(window);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003135 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3136
3137 window->assertNoEvents();
3138}
3139
Gang Wange9087892020-01-07 12:17:14 -05003140TEST_F(InputDispatcherTest, VerifyInputEvent_KeyEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003141 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Gang Wange9087892020-01-07 12:17:14 -05003142 sp<FakeWindowHandle> window =
3143 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3144
3145 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07003146 window->setFocusable(true);
Gang Wange9087892020-01-07 12:17:14 -05003147
Arthur Hung72d8dc32020-03-28 00:48:39 +00003148 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003149 setFocusedWindow(window);
3150
Gang Wange9087892020-01-07 12:17:14 -05003151 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
3152
3153 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3154 mDispatcher->notifyKey(&keyArgs);
3155
3156 InputEvent* event = window->consume();
3157 ASSERT_NE(event, nullptr);
3158
3159 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3160 ASSERT_NE(verified, nullptr);
3161 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::KEY);
3162
3163 ASSERT_EQ(keyArgs.eventTime, verified->eventTimeNanos);
3164 ASSERT_EQ(keyArgs.deviceId, verified->deviceId);
3165 ASSERT_EQ(keyArgs.source, verified->source);
3166 ASSERT_EQ(keyArgs.displayId, verified->displayId);
3167
3168 const VerifiedKeyEvent& verifiedKey = static_cast<const VerifiedKeyEvent&>(*verified);
3169
3170 ASSERT_EQ(keyArgs.action, verifiedKey.action);
Gang Wange9087892020-01-07 12:17:14 -05003171 ASSERT_EQ(keyArgs.flags & VERIFIED_KEY_EVENT_FLAGS, verifiedKey.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003172 ASSERT_EQ(keyArgs.downTime, verifiedKey.downTimeNanos);
Gang Wange9087892020-01-07 12:17:14 -05003173 ASSERT_EQ(keyArgs.keyCode, verifiedKey.keyCode);
3174 ASSERT_EQ(keyArgs.scanCode, verifiedKey.scanCode);
3175 ASSERT_EQ(keyArgs.metaState, verifiedKey.metaState);
3176 ASSERT_EQ(0, verifiedKey.repeatCount);
3177}
3178
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003179TEST_F(InputDispatcherTest, VerifyInputEvent_MotionEvent) {
Chris Yea209fde2020-07-22 13:54:51 -07003180 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003181 sp<FakeWindowHandle> window =
3182 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
3183
3184 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3185
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003186 ui::Transform transform;
3187 transform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3188
3189 gui::DisplayInfo displayInfo;
3190 displayInfo.displayId = ADISPLAY_ID_DEFAULT;
3191 displayInfo.transform = transform;
3192
3193 mDispatcher->onWindowInfosChanged({*window->getInfo()}, {displayInfo});
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003194
3195 NotifyMotionArgs motionArgs =
3196 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3197 ADISPLAY_ID_DEFAULT);
3198 mDispatcher->notifyMotion(&motionArgs);
3199
3200 InputEvent* event = window->consume();
3201 ASSERT_NE(event, nullptr);
3202
3203 std::unique_ptr<VerifiedInputEvent> verified = mDispatcher->verifyInputEvent(*event);
3204 ASSERT_NE(verified, nullptr);
3205 ASSERT_EQ(verified->type, VerifiedInputEvent::Type::MOTION);
3206
3207 EXPECT_EQ(motionArgs.eventTime, verified->eventTimeNanos);
3208 EXPECT_EQ(motionArgs.deviceId, verified->deviceId);
3209 EXPECT_EQ(motionArgs.source, verified->source);
3210 EXPECT_EQ(motionArgs.displayId, verified->displayId);
3211
3212 const VerifiedMotionEvent& verifiedMotion = static_cast<const VerifiedMotionEvent&>(*verified);
3213
Prabir Pradhanb5cb9572021-09-24 06:35:16 -07003214 const vec2 rawXY =
3215 MotionEvent::calculateTransformedXY(motionArgs.source, transform,
3216 motionArgs.pointerCoords[0].getXYValue());
3217 EXPECT_EQ(rawXY.x, verifiedMotion.rawX);
3218 EXPECT_EQ(rawXY.y, verifiedMotion.rawY);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003219 EXPECT_EQ(motionArgs.action & AMOTION_EVENT_ACTION_MASK, verifiedMotion.actionMasked);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003220 EXPECT_EQ(motionArgs.flags & VERIFIED_MOTION_EVENT_FLAGS, verifiedMotion.flags);
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08003221 EXPECT_EQ(motionArgs.downTime, verifiedMotion.downTimeNanos);
Siarhei Vishniakou47040bf2020-02-28 15:03:13 -08003222 EXPECT_EQ(motionArgs.metaState, verifiedMotion.metaState);
3223 EXPECT_EQ(motionArgs.buttonState, verifiedMotion.buttonState);
3224}
3225
chaviw09c8d2d2020-08-24 15:48:26 -07003226/**
3227 * Ensure that separate calls to sign the same data are generating the same key.
3228 * We avoid asserting against INVALID_HMAC. Since the key is random, there is a non-zero chance
3229 * that a specific key and data combination would produce INVALID_HMAC, which would cause flaky
3230 * tests.
3231 */
3232TEST_F(InputDispatcherTest, GeneratedHmac_IsConsistent) {
3233 KeyEvent event = getTestKeyEvent();
3234 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3235
3236 std::array<uint8_t, 32> hmac1 = mDispatcher->sign(verifiedEvent);
3237 std::array<uint8_t, 32> hmac2 = mDispatcher->sign(verifiedEvent);
3238 ASSERT_EQ(hmac1, hmac2);
3239}
3240
3241/**
3242 * Ensure that changes in VerifiedKeyEvent produce a different hmac.
3243 */
3244TEST_F(InputDispatcherTest, GeneratedHmac_ChangesWhenFieldsChange) {
3245 KeyEvent event = getTestKeyEvent();
3246 VerifiedKeyEvent verifiedEvent = verifiedKeyEventFromKeyEvent(event);
3247 std::array<uint8_t, 32> initialHmac = mDispatcher->sign(verifiedEvent);
3248
3249 verifiedEvent.deviceId += 1;
3250 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3251
3252 verifiedEvent.source += 1;
3253 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3254
3255 verifiedEvent.eventTimeNanos += 1;
3256 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3257
3258 verifiedEvent.displayId += 1;
3259 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3260
3261 verifiedEvent.action += 1;
3262 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3263
3264 verifiedEvent.downTimeNanos += 1;
3265 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3266
3267 verifiedEvent.flags += 1;
3268 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3269
3270 verifiedEvent.keyCode += 1;
3271 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3272
3273 verifiedEvent.scanCode += 1;
3274 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3275
3276 verifiedEvent.metaState += 1;
3277 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3278
3279 verifiedEvent.repeatCount += 1;
3280 ASSERT_NE(initialHmac, mDispatcher->sign(verifiedEvent));
3281}
3282
Vishnu Nair958da932020-08-21 17:12:37 -07003283TEST_F(InputDispatcherTest, SetFocusedWindow) {
3284 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3285 sp<FakeWindowHandle> windowTop =
3286 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3287 sp<FakeWindowHandle> windowSecond =
3288 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3289 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3290
3291 // Top window is also focusable but is not granted focus.
3292 windowTop->setFocusable(true);
3293 windowSecond->setFocusable(true);
3294 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3295 setFocusedWindow(windowSecond);
3296
3297 windowSecond->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003298 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3299 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003300
3301 // Focused window should receive event.
3302 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3303 windowTop->assertNoEvents();
3304}
3305
3306TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestInvalidChannel) {
3307 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3308 sp<FakeWindowHandle> window =
3309 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3310 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3311
3312 window->setFocusable(true);
3313 // Release channel for window is no longer valid.
3314 window->releaseChannel();
3315 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3316 setFocusedWindow(window);
3317
3318 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003319 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3320 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003321
3322 // window channel is invalid, so it should not receive any input event.
3323 window->assertNoEvents();
3324}
3325
3326TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestNoFocusableWindow) {
3327 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3328 sp<FakeWindowHandle> window =
3329 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003330 window->setFocusable(false);
Vishnu Nair958da932020-08-21 17:12:37 -07003331 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3332
Vishnu Nair958da932020-08-21 17:12:37 -07003333 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3334 setFocusedWindow(window);
3335
3336 // Test inject a key down, should timeout.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003337 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3338 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003339
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08003340 // window is not focusable, so it should not receive any input event.
Vishnu Nair958da932020-08-21 17:12:37 -07003341 window->assertNoEvents();
3342}
3343
3344TEST_F(InputDispatcherTest, SetFocusedWindow_CheckFocusedToken) {
3345 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3346 sp<FakeWindowHandle> windowTop =
3347 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3348 sp<FakeWindowHandle> windowSecond =
3349 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3350 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3351
3352 windowTop->setFocusable(true);
3353 windowSecond->setFocusable(true);
3354 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3355 setFocusedWindow(windowTop);
3356 windowTop->consumeFocusEvent(true);
3357
3358 setFocusedWindow(windowSecond, windowTop);
3359 windowSecond->consumeFocusEvent(true);
3360 windowTop->consumeFocusEvent(false);
3361
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003362 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3363 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003364
3365 // Focused window should receive event.
3366 windowSecond->consumeKeyDown(ADISPLAY_ID_NONE);
3367}
3368
3369TEST_F(InputDispatcherTest, SetFocusedWindow_DropRequestFocusTokenNotFocused) {
3370 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3371 sp<FakeWindowHandle> windowTop =
3372 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
3373 sp<FakeWindowHandle> windowSecond =
3374 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3375 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3376
3377 windowTop->setFocusable(true);
3378 windowSecond->setFocusable(true);
3379 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
3380 setFocusedWindow(windowSecond, windowTop);
3381
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003382 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
3383 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07003384
3385 // Event should be dropped.
3386 windowTop->assertNoEvents();
3387 windowSecond->assertNoEvents();
3388}
3389
3390TEST_F(InputDispatcherTest, SetFocusedWindow_DeferInvisibleWindow) {
3391 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3392 sp<FakeWindowHandle> window =
3393 new FakeWindowHandle(application, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
3394 sp<FakeWindowHandle> previousFocusedWindow =
3395 new FakeWindowHandle(application, mDispatcher, "previousFocusedWindow",
3396 ADISPLAY_ID_DEFAULT);
3397 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3398
3399 window->setFocusable(true);
3400 previousFocusedWindow->setFocusable(true);
3401 window->setVisible(false);
3402 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, previousFocusedWindow}}});
3403 setFocusedWindow(previousFocusedWindow);
3404 previousFocusedWindow->consumeFocusEvent(true);
3405
3406 // Requesting focus on invisible window takes focus from currently focused window.
3407 setFocusedWindow(window);
3408 previousFocusedWindow->consumeFocusEvent(false);
3409
3410 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003411 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07003412 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003413 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07003414
3415 // Window does not get focus event or key down.
3416 window->assertNoEvents();
3417
3418 // Window becomes visible.
3419 window->setVisible(true);
3420 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3421
3422 // Window receives focus event.
3423 window->consumeFocusEvent(true);
3424 // Focused window receives key down.
3425 window->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3426}
3427
Vishnu Nair599f1412021-06-21 10:39:58 -07003428TEST_F(InputDispatcherTest, DisplayRemoved) {
3429 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3430 sp<FakeWindowHandle> window =
3431 new FakeWindowHandle(application, mDispatcher, "window", ADISPLAY_ID_DEFAULT);
3432 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3433
3434 // window is granted focus.
3435 window->setFocusable(true);
3436 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
3437 setFocusedWindow(window);
3438 window->consumeFocusEvent(true);
3439
3440 // When a display is removed window loses focus.
3441 mDispatcher->displayRemoved(ADISPLAY_ID_DEFAULT);
3442 window->consumeFocusEvent(false);
3443}
3444
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003445/**
3446 * Launch two windows, with different owners. One window (slipperyExitWindow) has Flag::SLIPPERY,
3447 * and overlaps the other window, slipperyEnterWindow. The window 'slipperyExitWindow' is on top
3448 * of the 'slipperyEnterWindow'.
3449 *
3450 * Inject touch down into the top window. Upon receipt of the DOWN event, move the window in such
3451 * a way so that the touched location is no longer covered by the top window.
3452 *
3453 * Next, inject a MOVE event. Because the top window already moved earlier, this event is now
3454 * positioned over the bottom (slipperyEnterWindow) only. And because the top window had
3455 * Flag::SLIPPERY, this will cause the top window to lose the touch event (it will receive
3456 * ACTION_CANCEL instead), and the bottom window will receive a newly generated gesture (starting
3457 * with ACTION_DOWN).
3458 * Thus, the touch has been transferred from the top window into the bottom window, because the top
3459 * window moved itself away from the touched location and had Flag::SLIPPERY.
3460 *
3461 * Even though the top window moved away from the touched location, it is still obscuring the bottom
3462 * window. It's just not obscuring it at the touched location. That means, FLAG_WINDOW_IS_PARTIALLY_
3463 * OBSCURED should be set for the MotionEvent that reaches the bottom window.
3464 *
3465 * In this test, we ensure that the event received by the bottom window has
3466 * FLAG_WINDOW_IS_PARTIALLY_OBSCURED.
3467 */
3468TEST_F(InputDispatcherTest, SlipperyWindow_SetsFlagPartiallyObscured) {
Prabir Pradhan4df80f52022-04-05 18:33:16 +00003469 constexpr int32_t SLIPPERY_PID = INJECTOR_PID + 1;
3470 constexpr int32_t SLIPPERY_UID = INJECTOR_UID + 1;
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003471
3472 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
3473 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3474
3475 sp<FakeWindowHandle> slipperyExitWindow =
3476 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08003477 slipperyExitWindow->setSlippery(true);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003478 // Make sure this one overlaps the bottom window
3479 slipperyExitWindow->setFrame(Rect(25, 25, 75, 75));
3480 // Change the owner uid/pid of the window so that it is considered to be occluding the bottom
3481 // one. Windows with the same owner are not considered to be occluding each other.
3482 slipperyExitWindow->setOwnerInfo(SLIPPERY_PID, SLIPPERY_UID);
3483
3484 sp<FakeWindowHandle> slipperyEnterWindow =
3485 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
3486 slipperyExitWindow->setFrame(Rect(0, 0, 100, 100));
3487
3488 mDispatcher->setInputWindows(
3489 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3490
3491 // Use notifyMotion instead of injecting to avoid dealing with injection permissions
3492 NotifyMotionArgs args = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
3493 ADISPLAY_ID_DEFAULT, {{50, 50}});
3494 mDispatcher->notifyMotion(&args);
3495 slipperyExitWindow->consumeMotionDown();
3496 slipperyExitWindow->setFrame(Rect(70, 70, 100, 100));
3497 mDispatcher->setInputWindows(
3498 {{ADISPLAY_ID_DEFAULT, {slipperyExitWindow, slipperyEnterWindow}}});
3499
3500 args = generateMotionArgs(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3501 ADISPLAY_ID_DEFAULT, {{51, 51}});
3502 mDispatcher->notifyMotion(&args);
3503
3504 slipperyExitWindow->consumeMotionCancel();
3505
3506 slipperyEnterWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT,
3507 AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
3508}
3509
Garfield Tan1c7bc862020-01-28 13:24:04 -08003510class InputDispatcherKeyRepeatTest : public InputDispatcherTest {
3511protected:
3512 static constexpr nsecs_t KEY_REPEAT_TIMEOUT = 40 * 1000000; // 40 ms
3513 static constexpr nsecs_t KEY_REPEAT_DELAY = 40 * 1000000; // 40 ms
3514
Chris Yea209fde2020-07-22 13:54:51 -07003515 std::shared_ptr<FakeApplicationHandle> mApp;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003516 sp<FakeWindowHandle> mWindow;
3517
3518 virtual void SetUp() override {
3519 mFakePolicy = new FakeInputDispatcherPolicy();
3520 mFakePolicy->setKeyRepeatConfiguration(KEY_REPEAT_TIMEOUT, KEY_REPEAT_DELAY);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003521 mDispatcher = std::make_unique<InputDispatcher>(mFakePolicy);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003522 mDispatcher->setInputDispatchMode(/*enabled*/ true, /*frozen*/ false);
3523 ASSERT_EQ(OK, mDispatcher->start());
3524
3525 setUpWindow();
3526 }
3527
3528 void setUpWindow() {
Chris Yea209fde2020-07-22 13:54:51 -07003529 mApp = std::make_shared<FakeApplicationHandle>();
Garfield Tan1c7bc862020-01-28 13:24:04 -08003530 mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
3531
Vishnu Nair47074b82020-08-14 11:54:47 -07003532 mWindow->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003533 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003534 setFocusedWindow(mWindow);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003535 mWindow->consumeFocusEvent(true);
3536 }
3537
Chris Ye2ad95392020-09-01 13:44:44 -07003538 void sendAndConsumeKeyDown(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003539 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003540 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003541 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Otherwise it won't generate repeat event
3542 mDispatcher->notifyKey(&keyArgs);
3543
3544 // Window should receive key down event.
3545 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3546 }
3547
3548 void expectKeyRepeatOnce(int32_t repeatCount) {
3549 SCOPED_TRACE(StringPrintf("Checking event with repeat count %" PRId32, repeatCount));
3550 InputEvent* repeatEvent = mWindow->consume();
3551 ASSERT_NE(nullptr, repeatEvent);
3552
3553 uint32_t eventType = repeatEvent->getType();
3554 ASSERT_EQ(AINPUT_EVENT_TYPE_KEY, eventType);
3555
3556 KeyEvent* repeatKeyEvent = static_cast<KeyEvent*>(repeatEvent);
3557 uint32_t eventAction = repeatKeyEvent->getAction();
3558 EXPECT_EQ(AKEY_EVENT_ACTION_DOWN, eventAction);
3559 EXPECT_EQ(repeatCount, repeatKeyEvent->getRepeatCount());
3560 }
3561
Chris Ye2ad95392020-09-01 13:44:44 -07003562 void sendAndConsumeKeyUp(int32_t deviceId) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08003563 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
Chris Ye2ad95392020-09-01 13:44:44 -07003564 keyArgs.deviceId = deviceId;
Garfield Tan1c7bc862020-01-28 13:24:04 -08003565 keyArgs.policyFlags |= POLICY_FLAG_TRUSTED; // Unless it won't generate repeat event
3566 mDispatcher->notifyKey(&keyArgs);
3567
3568 // Window should receive key down event.
3569 mWindow->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT,
3570 0 /*expectedFlags*/);
3571 }
3572};
3573
3574TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeat) {
Chris Ye2ad95392020-09-01 13:44:44 -07003575 sendAndConsumeKeyDown(1 /* deviceId */);
3576 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3577 expectKeyRepeatOnce(repeatCount);
3578 }
3579}
3580
3581TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_ReceivesKeyRepeatFromTwoDevices) {
3582 sendAndConsumeKeyDown(1 /* deviceId */);
3583 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3584 expectKeyRepeatOnce(repeatCount);
3585 }
3586 sendAndConsumeKeyDown(2 /* deviceId */);
3587 /* repeatCount will start from 1 for deviceId 2 */
Garfield Tan1c7bc862020-01-28 13:24:04 -08003588 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3589 expectKeyRepeatOnce(repeatCount);
3590 }
3591}
3592
3593TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterUp) {
Chris Ye2ad95392020-09-01 13:44:44 -07003594 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003595 expectKeyRepeatOnce(1 /*repeatCount*/);
Chris Ye2ad95392020-09-01 13:44:44 -07003596 sendAndConsumeKeyUp(1 /* deviceId */);
3597 mWindow->assertNoEvents();
3598}
3599
3600TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatAfterStaleDeviceKeyUp) {
3601 sendAndConsumeKeyDown(1 /* deviceId */);
3602 expectKeyRepeatOnce(1 /*repeatCount*/);
3603 sendAndConsumeKeyDown(2 /* deviceId */);
3604 expectKeyRepeatOnce(1 /*repeatCount*/);
3605 // Stale key up from device 1.
3606 sendAndConsumeKeyUp(1 /* deviceId */);
3607 // Device 2 is still down, keep repeating
3608 expectKeyRepeatOnce(2 /*repeatCount*/);
3609 expectKeyRepeatOnce(3 /*repeatCount*/);
3610 // Device 2 key up
3611 sendAndConsumeKeyUp(2 /* deviceId */);
3612 mWindow->assertNoEvents();
3613}
3614
3615TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_KeyRepeatStopsAfterRepeatingKeyUp) {
3616 sendAndConsumeKeyDown(1 /* deviceId */);
3617 expectKeyRepeatOnce(1 /*repeatCount*/);
3618 sendAndConsumeKeyDown(2 /* deviceId */);
3619 expectKeyRepeatOnce(1 /*repeatCount*/);
3620 // Device 2 which holds the key repeating goes up, expect the repeating to stop.
3621 sendAndConsumeKeyUp(2 /* deviceId */);
3622 // Device 1 still holds key down, but the repeating was already stopped
Garfield Tan1c7bc862020-01-28 13:24:04 -08003623 mWindow->assertNoEvents();
3624}
3625
liushenxiang42232912021-05-21 20:24:09 +08003626TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_StopsKeyRepeatAfterDisableInputDevice) {
3627 sendAndConsumeKeyDown(DEVICE_ID);
3628 expectKeyRepeatOnce(1 /*repeatCount*/);
3629 NotifyDeviceResetArgs args(10 /*id*/, 20 /*eventTime*/, DEVICE_ID);
3630 mDispatcher->notifyDeviceReset(&args);
3631 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT,
3632 AKEY_EVENT_FLAG_CANCELED | AKEY_EVENT_FLAG_LONG_PRESS);
3633 mWindow->assertNoEvents();
3634}
3635
Garfield Tan1c7bc862020-01-28 13:24:04 -08003636TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseEventIdFromInputDispatcher) {
Chris Ye2ad95392020-09-01 13:44:44 -07003637 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003638 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3639 InputEvent* repeatEvent = mWindow->consume();
3640 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3641 EXPECT_EQ(IdGenerator::Source::INPUT_DISPATCHER,
3642 IdGenerator::getSource(repeatEvent->getId()));
3643 }
3644}
3645
3646TEST_F(InputDispatcherKeyRepeatTest, FocusedWindow_RepeatKeyEventsUseUniqueEventId) {
Chris Ye2ad95392020-09-01 13:44:44 -07003647 sendAndConsumeKeyDown(1 /* deviceId */);
Garfield Tan1c7bc862020-01-28 13:24:04 -08003648
3649 std::unordered_set<int32_t> idSet;
3650 for (int32_t repeatCount = 1; repeatCount <= 10; ++repeatCount) {
3651 InputEvent* repeatEvent = mWindow->consume();
3652 ASSERT_NE(nullptr, repeatEvent) << "Didn't receive event with repeat count " << repeatCount;
3653 int32_t id = repeatEvent->getId();
3654 EXPECT_EQ(idSet.end(), idSet.find(id));
3655 idSet.insert(id);
3656 }
3657}
3658
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003659/* Test InputDispatcher for MultiDisplay */
3660class InputDispatcherFocusOnTwoDisplaysTest : public InputDispatcherTest {
3661public:
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003662 virtual void SetUp() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003663 InputDispatcherTest::SetUp();
Arthur Hungb92218b2018-08-14 12:00:21 +08003664
Chris Yea209fde2020-07-22 13:54:51 -07003665 application1 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003666 windowInPrimary =
3667 new FakeWindowHandle(application1, mDispatcher, "D_1", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003668
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003669 // Set focus window for primary display, but focused display would be second one.
3670 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
Vishnu Nair47074b82020-08-14 11:54:47 -07003671 windowInPrimary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003672 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003673 setFocusedWindow(windowInPrimary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003674 windowInPrimary->consumeFocusEvent(true);
Arthur Hungb92218b2018-08-14 12:00:21 +08003675
Chris Yea209fde2020-07-22 13:54:51 -07003676 application2 = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003677 windowInSecondary =
3678 new FakeWindowHandle(application2, mDispatcher, "D_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003679 // Set focus to second display window.
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003680 // Set focus display to second one.
3681 mDispatcher->setFocusedDisplay(SECOND_DISPLAY_ID);
3682 // Set focus window for second display.
3683 mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
Vishnu Nair47074b82020-08-14 11:54:47 -07003684 windowInSecondary->setFocusable(true);
Arthur Hung72d8dc32020-03-28 00:48:39 +00003685 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
Vishnu Nair958da932020-08-21 17:12:37 -07003686 setFocusedWindow(windowInSecondary);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003687 windowInSecondary->consumeFocusEvent(true);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003688 }
3689
Prabir Pradhan3608aad2019-10-02 17:08:26 -07003690 virtual void TearDown() override {
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003691 InputDispatcherTest::TearDown();
3692
Chris Yea209fde2020-07-22 13:54:51 -07003693 application1.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003694 windowInPrimary.clear();
Chris Yea209fde2020-07-22 13:54:51 -07003695 application2.reset();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003696 windowInSecondary.clear();
3697 }
3698
3699protected:
Chris Yea209fde2020-07-22 13:54:51 -07003700 std::shared_ptr<FakeApplicationHandle> application1;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003701 sp<FakeWindowHandle> windowInPrimary;
Chris Yea209fde2020-07-22 13:54:51 -07003702 std::shared_ptr<FakeApplicationHandle> application2;
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003703 sp<FakeWindowHandle> windowInSecondary;
3704};
3705
3706TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayTouch) {
3707 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003708 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3709 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3710 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003711 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hungb92218b2018-08-14 12:00:21 +08003712 windowInSecondary->assertNoEvents();
3713
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003714 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003715 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3716 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3717 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003718 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003719 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hungb92218b2018-08-14 12:00:21 +08003720}
3721
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003722TEST_F(InputDispatcherFocusOnTwoDisplaysTest, SetInputWindow_MultiDisplayFocus) {
Tiger Huang721e26f2018-07-24 22:26:19 +08003723 // Test inject a key down with display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003724 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3725 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003726 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003727 windowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Tiger Huang721e26f2018-07-24 22:26:19 +08003728 windowInSecondary->assertNoEvents();
3729
3730 // Test inject a key down without display id specified.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003731 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003732 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hungb92218b2018-08-14 12:00:21 +08003733 windowInPrimary->assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003734 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hungb92218b2018-08-14 12:00:21 +08003735
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08003736 // Remove all windows in secondary display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00003737 mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
Arthur Hungb92218b2018-08-14 12:00:21 +08003738
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003739 // Old focus should receive a cancel event.
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003740 windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
3741 AKEY_EVENT_FLAG_CANCELED);
Arthur Hungb92218b2018-08-14 12:00:21 +08003742
3743 // Test inject a key down, should timeout because of no target window.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08003744 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDownNoRepeat(mDispatcher))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003745 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Arthur Hungb92218b2018-08-14 12:00:21 +08003746 windowInPrimary->assertNoEvents();
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01003747 windowInSecondary->consumeFocusEvent(false);
Arthur Hungb92218b2018-08-14 12:00:21 +08003748 windowInSecondary->assertNoEvents();
3749}
3750
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003751// Test per-display input monitors for motion event.
3752TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorMotionEvent_MultiDisplay) {
chaviwd1c23182019-12-20 18:44:56 -08003753 FakeMonitorReceiver monitorInPrimary =
3754 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3755 FakeMonitorReceiver monitorInSecondary =
3756 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003757
3758 // Test touch down on primary display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003759 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3760 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3761 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003762 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
chaviwd1c23182019-12-20 18:44:56 -08003763 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003764 windowInSecondary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003765 monitorInSecondary.assertNoEvents();
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003766
3767 // Test touch down on second display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003768 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3769 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3770 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003771 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003772 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003773 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
chaviwd1c23182019-12-20 18:44:56 -08003774 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003775
3776 // Test inject a non-pointer motion event.
3777 // If specific a display, it will dispatch to the focused window of particular display,
3778 // or it will dispatch to the focused window of focused display.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003779 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3780 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_NONE))
3781 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003782 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003783 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003784 windowInSecondary->consumeMotionDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003785 monitorInSecondary.consumeMotionDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003786}
3787
3788// Test per-display input monitors for key event.
3789TEST_F(InputDispatcherFocusOnTwoDisplaysTest, MonitorKeyEvent_MultiDisplay) {
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003790 // Input monitor per display.
chaviwd1c23182019-12-20 18:44:56 -08003791 FakeMonitorReceiver monitorInPrimary =
3792 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3793 FakeMonitorReceiver monitorInSecondary =
3794 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003795
3796 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003797 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
3798 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003799 windowInPrimary->assertNoEvents();
chaviwd1c23182019-12-20 18:44:56 -08003800 monitorInPrimary.assertNoEvents();
Siarhei Vishniakouc5ca85c2019-11-15 17:20:00 -08003801 windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
chaviwd1c23182019-12-20 18:44:56 -08003802 monitorInSecondary.consumeKeyDown(ADISPLAY_ID_NONE);
Arthur Hung2fbf37f2018-09-13 18:16:41 +08003803}
3804
Vishnu Nair958da932020-08-21 17:12:37 -07003805TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CanFocusWindowOnUnfocusedDisplay) {
3806 sp<FakeWindowHandle> secondWindowInPrimary =
3807 new FakeWindowHandle(application1, mDispatcher, "D_1_W2", ADISPLAY_ID_DEFAULT);
3808 secondWindowInPrimary->setFocusable(true);
3809 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary, secondWindowInPrimary}}});
3810 setFocusedWindow(secondWindowInPrimary);
3811 windowInPrimary->consumeFocusEvent(false);
3812 secondWindowInPrimary->consumeFocusEvent(true);
3813
3814 // Test inject a key down.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08003815 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
3816 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07003817 windowInPrimary->assertNoEvents();
3818 windowInSecondary->assertNoEvents();
3819 secondWindowInPrimary->consumeKeyDown(ADISPLAY_ID_DEFAULT);
3820}
3821
Arthur Hungdfd528e2021-12-08 13:23:04 +00003822TEST_F(InputDispatcherFocusOnTwoDisplaysTest, CancelTouch_MultiDisplay) {
3823 FakeMonitorReceiver monitorInPrimary =
3824 FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
3825 FakeMonitorReceiver monitorInSecondary =
3826 FakeMonitorReceiver(mDispatcher, "M_2", SECOND_DISPLAY_ID);
3827
3828 // Test touch down on primary display.
3829 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3830 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
3831 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3832 windowInPrimary->consumeMotionDown(ADISPLAY_ID_DEFAULT);
3833 monitorInPrimary.consumeMotionDown(ADISPLAY_ID_DEFAULT);
3834
3835 // Test touch down on second display.
3836 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
3837 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, SECOND_DISPLAY_ID))
3838 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
3839 windowInSecondary->consumeMotionDown(SECOND_DISPLAY_ID);
3840 monitorInSecondary.consumeMotionDown(SECOND_DISPLAY_ID);
3841
3842 // Trigger cancel touch.
3843 mDispatcher->cancelCurrentTouch();
3844 windowInPrimary->consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3845 monitorInPrimary.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
3846 windowInSecondary->consumeMotionCancel(SECOND_DISPLAY_ID);
3847 monitorInSecondary.consumeMotionCancel(SECOND_DISPLAY_ID);
3848
3849 // Test inject a move motion event, no window/monitor should receive the event.
3850 ASSERT_EQ(InputEventInjectionResult::FAILED,
3851 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3852 ADISPLAY_ID_DEFAULT, {110, 200}))
3853 << "Inject motion event should return InputEventInjectionResult::FAILED";
3854 windowInPrimary->assertNoEvents();
3855 monitorInPrimary.assertNoEvents();
3856
3857 ASSERT_EQ(InputEventInjectionResult::FAILED,
3858 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
3859 SECOND_DISPLAY_ID, {110, 200}))
3860 << "Inject motion event should return InputEventInjectionResult::FAILED";
3861 windowInSecondary->assertNoEvents();
3862 monitorInSecondary.assertNoEvents();
3863}
3864
Jackal Guof9696682018-10-05 12:23:23 +08003865class InputFilterTest : public InputDispatcherTest {
3866protected:
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003867 void testNotifyMotion(int32_t displayId, bool expectToBeFiltered,
3868 const ui::Transform& transform = ui::Transform()) {
Jackal Guof9696682018-10-05 12:23:23 +08003869 NotifyMotionArgs motionArgs;
3870
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003871 motionArgs =
3872 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003873 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10003874 motionArgs =
3875 generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN, displayId);
Jackal Guof9696682018-10-05 12:23:23 +08003876 mDispatcher->notifyMotion(&motionArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003877 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003878 if (expectToBeFiltered) {
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003879 const auto xy = transform.transform(motionArgs.pointerCoords->getXYValue());
3880 mFakePolicy->assertFilterInputEventWasCalled(motionArgs, xy);
Jackal Guof9696682018-10-05 12:23:23 +08003881 } else {
3882 mFakePolicy->assertFilterInputEventWasNotCalled();
3883 }
3884 }
3885
3886 void testNotifyKey(bool expectToBeFiltered) {
3887 NotifyKeyArgs keyArgs;
3888
3889 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
3890 mDispatcher->notifyKey(&keyArgs);
3891 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP);
3892 mDispatcher->notifyKey(&keyArgs);
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08003893 ASSERT_TRUE(mDispatcher->waitForIdle());
Jackal Guof9696682018-10-05 12:23:23 +08003894
3895 if (expectToBeFiltered) {
Siarhei Vishniakou8935a802019-11-15 16:41:44 -08003896 mFakePolicy->assertFilterInputEventWasCalled(keyArgs);
Jackal Guof9696682018-10-05 12:23:23 +08003897 } else {
3898 mFakePolicy->assertFilterInputEventWasNotCalled();
3899 }
3900 }
3901};
3902
3903// Test InputFilter for MotionEvent
3904TEST_F(InputFilterTest, MotionEvent_InputFilter) {
3905 // Since the InputFilter is disabled by default, check if touch events aren't filtered.
3906 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3907 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3908
3909 // Enable InputFilter
3910 mDispatcher->setInputFilterEnabled(true);
3911 // Test touch on both primary and second display, and check if both events are filtered.
3912 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true);
3913 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true);
3914
3915 // Disable InputFilter
3916 mDispatcher->setInputFilterEnabled(false);
3917 // Test touch on both primary and second display, and check if both events aren't filtered.
3918 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ false);
3919 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ false);
3920}
3921
3922// Test InputFilter for KeyEvent
3923TEST_F(InputFilterTest, KeyEvent_InputFilter) {
3924 // Since the InputFilter is disabled by default, check if key event aren't filtered.
3925 testNotifyKey(/*expectToBeFiltered*/ false);
3926
3927 // Enable InputFilter
3928 mDispatcher->setInputFilterEnabled(true);
3929 // Send a key event, and check if it is filtered.
3930 testNotifyKey(/*expectToBeFiltered*/ true);
3931
3932 // Disable InputFilter
3933 mDispatcher->setInputFilterEnabled(false);
3934 // Send a key event, and check if it isn't filtered.
3935 testNotifyKey(/*expectToBeFiltered*/ false);
3936}
3937
Prabir Pradhan81420cc2021-09-06 10:28:50 -07003938// Ensure that MotionEvents sent to the InputFilter through InputListener are converted to the
3939// logical display coordinate space.
3940TEST_F(InputFilterTest, MotionEvent_UsesLogicalDisplayCoordinates_notifyMotion) {
3941 ui::Transform firstDisplayTransform;
3942 firstDisplayTransform.set({1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 0, 0, 1});
3943 ui::Transform secondDisplayTransform;
3944 secondDisplayTransform.set({-6.6, -5.5, -4.4, -3.3, -2.2, -1.1, 0, 0, 1});
3945
3946 std::vector<gui::DisplayInfo> displayInfos(2);
3947 displayInfos[0].displayId = ADISPLAY_ID_DEFAULT;
3948 displayInfos[0].transform = firstDisplayTransform;
3949 displayInfos[1].displayId = SECOND_DISPLAY_ID;
3950 displayInfos[1].transform = secondDisplayTransform;
3951
3952 mDispatcher->onWindowInfosChanged({}, displayInfos);
3953
3954 // Enable InputFilter
3955 mDispatcher->setInputFilterEnabled(true);
3956
3957 // Ensure the correct transforms are used for the displays.
3958 testNotifyMotion(ADISPLAY_ID_DEFAULT, /*expectToBeFiltered*/ true, firstDisplayTransform);
3959 testNotifyMotion(SECOND_DISPLAY_ID, /*expectToBeFiltered*/ true, secondDisplayTransform);
3960}
3961
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003962class InputFilterInjectionPolicyTest : public InputDispatcherTest {
3963protected:
3964 virtual void SetUp() override {
3965 InputDispatcherTest::SetUp();
3966
3967 /**
3968 * We don't need to enable input filter to test the injected event policy, but we enabled it
3969 * here to make the tests more realistic, since this policy only matters when inputfilter is
3970 * on.
3971 */
3972 mDispatcher->setInputFilterEnabled(true);
3973
3974 std::shared_ptr<InputApplicationHandle> application =
3975 std::make_shared<FakeApplicationHandle>();
3976 mWindow =
3977 new FakeWindowHandle(application, mDispatcher, "Test Window", ADISPLAY_ID_DEFAULT);
3978
3979 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
3980 mWindow->setFocusable(true);
3981 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
3982 setFocusedWindow(mWindow);
3983 mWindow->consumeFocusEvent(true);
3984 }
3985
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00003986 void testInjectedKey(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
3987 int32_t flags) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003988 KeyEvent event;
3989
3990 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
3991 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_KEYBOARD,
3992 ADISPLAY_ID_NONE, INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, 0, AKEYCODE_A,
3993 KEY_A, AMETA_NONE, 0 /*repeatCount*/, eventTime, eventTime);
3994 const int32_t additionalPolicyFlags =
3995 POLICY_FLAG_PASS_TO_USER | POLICY_FLAG_DISABLE_KEY_REPEAT;
3996 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan4df80f52022-04-05 18:33:16 +00003997 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00003998 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
3999 policyFlags | additionalPolicyFlags));
4000
4001 InputEvent* received = mWindow->consume();
4002 ASSERT_NE(nullptr, received);
4003 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004004 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_KEY);
4005 KeyEvent& keyEvent = static_cast<KeyEvent&>(*received);
4006 ASSERT_EQ(flags, keyEvent.getFlags());
4007 }
4008
4009 void testInjectedMotion(int32_t policyFlags, int32_t injectedDeviceId, int32_t resolvedDeviceId,
4010 int32_t flags) {
4011 MotionEvent event;
4012 PointerProperties pointerProperties[1];
4013 PointerCoords pointerCoords[1];
4014 pointerProperties[0].clear();
4015 pointerProperties[0].id = 0;
4016 pointerCoords[0].clear();
4017 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, 300);
4018 pointerCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, 400);
4019
4020 ui::Transform identityTransform;
4021 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC);
4022 event.initialize(InputEvent::nextId(), injectedDeviceId, AINPUT_SOURCE_TOUCHSCREEN,
4023 DISPLAY_ID, INVALID_HMAC, AMOTION_EVENT_ACTION_DOWN, 0, 0,
4024 AMOTION_EVENT_EDGE_FLAG_NONE, AMETA_NONE, 0, MotionClassification::NONE,
4025 identityTransform, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07004026 AMOTION_EVENT_INVALID_CURSOR_POSITION, identityTransform, eventTime,
Evan Rosky09576692021-07-01 12:22:09 -07004027 eventTime,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004028 /*pointerCount*/ 1, pointerProperties, pointerCoords);
4029
4030 const int32_t additionalPolicyFlags = POLICY_FLAG_PASS_TO_USER;
4031 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhan4df80f52022-04-05 18:33:16 +00004032 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004033 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms,
4034 policyFlags | additionalPolicyFlags));
4035
4036 InputEvent* received = mWindow->consume();
4037 ASSERT_NE(nullptr, received);
4038 ASSERT_EQ(resolvedDeviceId, received->getDeviceId());
4039 ASSERT_EQ(received->getType(), AINPUT_EVENT_TYPE_MOTION);
4040 MotionEvent& motionEvent = static_cast<MotionEvent&>(*received);
4041 ASSERT_EQ(flags, motionEvent.getFlags());
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004042 }
4043
4044private:
4045 sp<FakeWindowHandle> mWindow;
4046};
4047
4048TEST_F(InputFilterInjectionPolicyTest, TrustedFilteredEvents_KeepOriginalDeviceId) {
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004049 // Must have POLICY_FLAG_FILTERED here to indicate that the event has gone through the input
4050 // filter. Without it, the event will no different from a regularly injected event, and the
4051 // injected device id will be overwritten.
4052 testInjectedKey(POLICY_FLAG_FILTERED, 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4053 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004054}
4055
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004056TEST_F(InputFilterInjectionPolicyTest, KeyEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004057 testInjectedKey(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004058 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4059 AKEY_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
4060}
4061
4062TEST_F(InputFilterInjectionPolicyTest,
4063 MotionEventsInjectedFromAccessibility_HaveAccessibilityFlag) {
4064 testInjectedMotion(POLICY_FLAG_FILTERED | POLICY_FLAG_INJECTED_FROM_ACCESSIBILITY,
4065 3 /*injectedDeviceId*/, 3 /*resolvedDeviceId*/,
4066 AMOTION_EVENT_FLAG_IS_ACCESSIBILITY_EVENT);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004067}
4068
4069TEST_F(InputFilterInjectionPolicyTest, RegularInjectedEvents_ReceiveVirtualDeviceId) {
4070 testInjectedKey(0 /*policyFlags*/, 3 /*injectedDeviceId*/,
Siarhei Vishniakouf00a4ec2021-06-16 03:55:32 +00004071 VIRTUAL_KEYBOARD_ID /*resolvedDeviceId*/, 0 /*flags*/);
Siarhei Vishniakou5d552c42021-05-21 05:02:22 +00004072}
4073
chaviwfd6d3512019-03-25 13:23:49 -07004074class InputDispatcherOnPointerDownOutsideFocus : public InputDispatcherTest {
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004075 virtual void SetUp() override {
chaviwfd6d3512019-03-25 13:23:49 -07004076 InputDispatcherTest::SetUp();
4077
Chris Yea209fde2020-07-22 13:54:51 -07004078 std::shared_ptr<FakeApplicationHandle> application =
4079 std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004080 mUnfocusedWindow =
4081 new FakeWindowHandle(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004082 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
chaviwfd6d3512019-03-25 13:23:49 -07004083
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004084 mFocusedWindow =
4085 new FakeWindowHandle(application, mDispatcher, "Second", ADISPLAY_ID_DEFAULT);
4086 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
chaviwfd6d3512019-03-25 13:23:49 -07004087
4088 // Set focused application.
4089 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
Vishnu Nair47074b82020-08-14 11:54:47 -07004090 mFocusedWindow->setFocusable(true);
chaviwfd6d3512019-03-25 13:23:49 -07004091
4092 // Expect one focus window exist in display.
Arthur Hung72d8dc32020-03-28 00:48:39 +00004093 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004094 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004095 mFocusedWindow->consumeFocusEvent(true);
chaviwfd6d3512019-03-25 13:23:49 -07004096 }
4097
Prabir Pradhan3608aad2019-10-02 17:08:26 -07004098 virtual void TearDown() override {
chaviwfd6d3512019-03-25 13:23:49 -07004099 InputDispatcherTest::TearDown();
4100
4101 mUnfocusedWindow.clear();
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004102 mFocusedWindow.clear();
chaviwfd6d3512019-03-25 13:23:49 -07004103 }
4104
4105protected:
4106 sp<FakeWindowHandle> mUnfocusedWindow;
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004107 sp<FakeWindowHandle> mFocusedWindow;
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004108 static constexpr PointF FOCUSED_WINDOW_TOUCH_POINT = {60, 60};
chaviwfd6d3512019-03-25 13:23:49 -07004109};
4110
4111// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4112// DOWN on the window that doesn't have focus. Ensure the window that didn't have focus received
4113// the onPointerDownOutsideFocus callback.
4114TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_Success) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004115 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004116 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4117 {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004118 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004119 mUnfocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004120
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004121 ASSERT_TRUE(mDispatcher->waitForIdle());
chaviwfd6d3512019-03-25 13:23:49 -07004122 mFakePolicy->assertOnPointerDownEquals(mUnfocusedWindow->getToken());
4123}
4124
4125// Have two windows, one with focus. Inject MotionEvent with source TRACKBALL and action
4126// DOWN on the window that doesn't have focus. Ensure no window received the
4127// onPointerDownOutsideFocus callback.
4128TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonPointerSource) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004129 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004130 injectMotionDown(mDispatcher, AINPUT_SOURCE_TRACKBALL, ADISPLAY_ID_DEFAULT, {20, 20}))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004131 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004132 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004133
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004134 ASSERT_TRUE(mDispatcher->waitForIdle());
4135 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004136}
4137
4138// Have two windows, one with focus. Inject KeyEvent with action DOWN on the window that doesn't
4139// have focus. Ensure no window received the onPointerDownOutsideFocus callback.
4140TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_NonMotionFailure) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004141 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4142 injectKeyDownNoRepeat(mDispatcher, ADISPLAY_ID_DEFAULT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004143 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004144 mFocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
chaviwfd6d3512019-03-25 13:23:49 -07004145
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004146 ASSERT_TRUE(mDispatcher->waitForIdle());
4147 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004148}
4149
4150// Have two windows, one with focus. Inject MotionEvent with source TOUCHSCREEN and action
4151// DOWN on the window that already has focus. Ensure no window received the
4152// onPointerDownOutsideFocus callback.
Siarhei Vishniakou870ecec2020-12-09 08:07:46 -10004153TEST_F(InputDispatcherOnPointerDownOutsideFocus, OnPointerDownOutsideFocus_OnAlreadyFocusedWindow) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004154 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoub9b15352019-11-26 13:19:26 -08004155 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakoufb9fcda2020-05-04 14:59:19 -07004156 FOCUSED_WINDOW_TOUCH_POINT))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004157 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakou03aee2a2020-04-13 20:44:54 -07004158 mFocusedWindow->consumeMotionDown();
chaviwfd6d3512019-03-25 13:23:49 -07004159
Siarhei Vishniakou2bfa9052019-11-21 18:10:54 -08004160 ASSERT_TRUE(mDispatcher->waitForIdle());
4161 mFakePolicy->assertOnPointerDownWasNotCalled();
chaviwfd6d3512019-03-25 13:23:49 -07004162}
4163
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08004164// Have two windows, one with focus. Injecting a trusted DOWN MotionEvent with the flag
4165// NO_FOCUS_CHANGE on the unfocused window should not call the onPointerDownOutsideFocus callback.
4166TEST_F(InputDispatcherOnPointerDownOutsideFocus, NoFocusChangeFlag) {
4167 const MotionEvent event =
4168 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_MOUSE)
4169 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
4170 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(20).y(20))
4171 .addFlag(AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE)
4172 .build();
4173 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectMotionEvent(mDispatcher, event))
4174 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
4175 mUnfocusedWindow->consumeAnyMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE);
4176
4177 ASSERT_TRUE(mDispatcher->waitForIdle());
4178 mFakePolicy->assertOnPointerDownWasNotCalled();
4179 // Ensure that the unfocused window did not receive any FOCUS events.
4180 mUnfocusedWindow->assertNoEvents();
4181}
4182
chaviwaf87b3e2019-10-01 16:59:28 -07004183// These tests ensures we can send touch events to a single client when there are multiple input
4184// windows that point to the same client token.
4185class InputDispatcherMultiWindowSameTokenTests : public InputDispatcherTest {
4186 virtual void SetUp() override {
4187 InputDispatcherTest::SetUp();
4188
Chris Yea209fde2020-07-22 13:54:51 -07004189 std::shared_ptr<FakeApplicationHandle> application =
4190 std::make_shared<FakeApplicationHandle>();
chaviwaf87b3e2019-10-01 16:59:28 -07004191 mWindow1 = new FakeWindowHandle(application, mDispatcher, "Fake Window 1",
4192 ADISPLAY_ID_DEFAULT);
chaviwaf87b3e2019-10-01 16:59:28 -07004193 mWindow1->setFrame(Rect(0, 0, 100, 100));
4194
4195 mWindow2 = new FakeWindowHandle(application, mDispatcher, "Fake Window 2",
4196 ADISPLAY_ID_DEFAULT, mWindow1->getToken());
chaviwaf87b3e2019-10-01 16:59:28 -07004197 mWindow2->setFrame(Rect(100, 100, 200, 200));
4198
Arthur Hung72d8dc32020-03-28 00:48:39 +00004199 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
chaviwaf87b3e2019-10-01 16:59:28 -07004200 }
4201
4202protected:
4203 sp<FakeWindowHandle> mWindow1;
4204 sp<FakeWindowHandle> mWindow2;
4205
4206 // Helper function to convert the point from screen coordinates into the window's space
chaviw3277faf2021-05-19 16:45:23 -05004207 static PointF getPointInWindow(const WindowInfo* windowInfo, const PointF& point) {
chaviw1ff3d1e2020-07-01 15:53:47 -07004208 vec2 vals = windowInfo->transform.transform(point.x, point.y);
4209 return {vals.x, vals.y};
chaviwaf87b3e2019-10-01 16:59:28 -07004210 }
4211
4212 void consumeMotionEvent(const sp<FakeWindowHandle>& window, int32_t expectedAction,
4213 const std::vector<PointF>& points) {
Siarhei Vishniakouf1035d42019-09-20 16:32:01 +01004214 const std::string name = window->getName();
chaviwaf87b3e2019-10-01 16:59:28 -07004215 InputEvent* event = window->consume();
4216
4217 ASSERT_NE(nullptr, event) << name.c_str()
4218 << ": consumer should have returned non-NULL event.";
4219
4220 ASSERT_EQ(AINPUT_EVENT_TYPE_MOTION, event->getType())
4221 << name.c_str() << "expected " << inputEventTypeToString(AINPUT_EVENT_TYPE_MOTION)
4222 << " event, got " << inputEventTypeToString(event->getType()) << " event";
4223
4224 const MotionEvent& motionEvent = static_cast<const MotionEvent&>(*event);
Siarhei Vishniakouca205502021-07-16 21:31:58 +00004225 assertMotionAction(expectedAction, motionEvent.getAction());
chaviwaf87b3e2019-10-01 16:59:28 -07004226
4227 for (size_t i = 0; i < points.size(); i++) {
4228 float expectedX = points[i].x;
4229 float expectedY = points[i].y;
4230
4231 EXPECT_EQ(expectedX, motionEvent.getX(i))
4232 << "expected " << expectedX << " for x[" << i << "] coord of " << name.c_str()
4233 << ", got " << motionEvent.getX(i);
4234 EXPECT_EQ(expectedY, motionEvent.getY(i))
4235 << "expected " << expectedY << " for y[" << i << "] coord of " << name.c_str()
4236 << ", got " << motionEvent.getY(i);
4237 }
4238 }
chaviw9eaa22c2020-07-01 16:21:27 -07004239
Siarhei Vishniakouf355bf92021-12-09 10:43:21 -08004240 void touchAndAssertPositions(int32_t action, const std::vector<PointF>& touchedPoints,
chaviw9eaa22c2020-07-01 16:21:27 -07004241 std::vector<PointF> expectedPoints) {
4242 NotifyMotionArgs motionArgs = generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN,
4243 ADISPLAY_ID_DEFAULT, touchedPoints);
4244 mDispatcher->notifyMotion(&motionArgs);
4245
4246 // Always consume from window1 since it's the window that has the InputReceiver
4247 consumeMotionEvent(mWindow1, action, expectedPoints);
4248 }
chaviwaf87b3e2019-10-01 16:59:28 -07004249};
4250
4251TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchSameScale) {
4252 // Touch Window 1
4253 PointF touchedPoint = {10, 10};
4254 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004255 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004256
4257 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004258 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004259
4260 // Touch Window 2
4261 touchedPoint = {150, 150};
4262 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004263 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004264}
4265
chaviw9eaa22c2020-07-01 16:21:27 -07004266TEST_F(InputDispatcherMultiWindowSameTokenTests, SingleTouchDifferentTransform) {
4267 // Set scale value for window2
chaviwaf87b3e2019-10-01 16:59:28 -07004268 mWindow2->setWindowScale(0.5f, 0.5f);
4269
4270 // Touch Window 1
4271 PointF touchedPoint = {10, 10};
4272 PointF expectedPoint = getPointInWindow(mWindow1->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004273 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004274 // Release touch on Window 1
chaviw9eaa22c2020-07-01 16:21:27 -07004275 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004276
4277 // Touch Window 2
4278 touchedPoint = {150, 150};
4279 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
chaviw9eaa22c2020-07-01 16:21:27 -07004280 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
4281 touchAndAssertPositions(AMOTION_EVENT_ACTION_UP, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004282
chaviw9eaa22c2020-07-01 16:21:27 -07004283 // Update the transform so rotation is set
4284 mWindow2->setWindowTransform(0, -1, 1, 0);
4285 expectedPoint = getPointInWindow(mWindow2->getInfo(), touchedPoint);
4286 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, {touchedPoint}, {expectedPoint});
chaviwaf87b3e2019-10-01 16:59:28 -07004287}
4288
chaviw9eaa22c2020-07-01 16:21:27 -07004289TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004290 mWindow2->setWindowScale(0.5f, 0.5f);
4291
4292 // Touch Window 1
4293 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4294 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004295 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004296
4297 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004298 touchedPoints.push_back(PointF{150, 150});
4299 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004300 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004301
chaviw9eaa22c2020-07-01 16:21:27 -07004302 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004303 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004304 expectedPoints.pop_back();
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004305
chaviw9eaa22c2020-07-01 16:21:27 -07004306 // Update the transform so rotation is set for Window 2
4307 mWindow2->setWindowTransform(0, -1, 1, 0);
4308 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004309 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004310}
4311
chaviw9eaa22c2020-07-01 16:21:27 -07004312TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleTouchMoveDifferentTransform) {
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004313 mWindow2->setWindowScale(0.5f, 0.5f);
4314
4315 // Touch Window 1
4316 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4317 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004318 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004319
4320 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004321 touchedPoints.push_back(PointF{150, 150});
4322 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004323
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004324 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004325
4326 // Move both windows
4327 touchedPoints = {{20, 20}, {175, 175}};
4328 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4329 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4330
chaviw9eaa22c2020-07-01 16:21:27 -07004331 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004332
chaviw9eaa22c2020-07-01 16:21:27 -07004333 // Release Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004334 touchAndAssertPositions(POINTER_1_UP, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004335 expectedPoints.pop_back();
4336
4337 // Touch Window 2
4338 mWindow2->setWindowTransform(0, -1, 1, 0);
4339 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004340 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
chaviw9eaa22c2020-07-01 16:21:27 -07004341
4342 // Move both windows
4343 touchedPoints = {{20, 20}, {175, 175}};
4344 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4345 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4346
4347 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004348}
4349
4350TEST_F(InputDispatcherMultiWindowSameTokenTests, MultipleWindowsFirstTouchWithScale) {
4351 mWindow1->setWindowScale(0.5f, 0.5f);
4352
4353 // Touch Window 1
4354 std::vector<PointF> touchedPoints = {PointF{10, 10}};
4355 std::vector<PointF> expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0])};
chaviw9eaa22c2020-07-01 16:21:27 -07004356 touchAndAssertPositions(AMOTION_EVENT_ACTION_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004357
4358 // Touch Window 2
chaviw9eaa22c2020-07-01 16:21:27 -07004359 touchedPoints.push_back(PointF{150, 150});
4360 expectedPoints.push_back(getPointInWindow(mWindow2->getInfo(), touchedPoints[1]));
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004361
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08004362 touchAndAssertPositions(POINTER_1_DOWN, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004363
4364 // Move both windows
4365 touchedPoints = {{20, 20}, {175, 175}};
4366 expectedPoints = {getPointInWindow(mWindow1->getInfo(), touchedPoints[0]),
4367 getPointInWindow(mWindow2->getInfo(), touchedPoints[1])};
4368
chaviw9eaa22c2020-07-01 16:21:27 -07004369 touchAndAssertPositions(AMOTION_EVENT_ACTION_MOVE, touchedPoints, expectedPoints);
Chavi Weingarten65f98b82020-01-16 18:56:50 +00004370}
4371
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004372class InputDispatcherSingleWindowAnr : public InputDispatcherTest {
4373 virtual void SetUp() override {
4374 InputDispatcherTest::SetUp();
4375
Chris Yea209fde2020-07-22 13:54:51 -07004376 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004377 mApplication->setDispatchingTimeout(20ms);
4378 mWindow =
4379 new FakeWindowHandle(mApplication, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
4380 mWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004381 mWindow->setDispatchingTimeout(30ms);
Vishnu Nair47074b82020-08-14 11:54:47 -07004382 mWindow->setFocusable(true);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004383
4384 // Set focused application.
4385 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
4386
4387 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004388 setFocusedWindow(mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004389 mWindow->consumeFocusEvent(true);
4390 }
4391
4392 virtual void TearDown() override {
4393 InputDispatcherTest::TearDown();
4394 mWindow.clear();
4395 }
4396
4397protected:
Chris Yea209fde2020-07-22 13:54:51 -07004398 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004399 sp<FakeWindowHandle> mWindow;
4400 static constexpr PointF WINDOW_LOCATION = {20, 20};
4401
4402 void tapOnWindow() {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004403 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004404 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4405 WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004406 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004407 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4408 WINDOW_LOCATION));
4409 }
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004410
4411 sp<FakeWindowHandle> addSpyWindow() {
4412 sp<FakeWindowHandle> spy =
4413 new FakeWindowHandle(mApplication, mDispatcher, "Spy", ADISPLAY_ID_DEFAULT);
4414 spy->setTrustedOverlay(true);
4415 spy->setFocusable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08004416 spy->setSpy(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004417 spy->setDispatchingTimeout(30ms);
4418 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, mWindow}}});
4419 return spy;
4420 }
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004421};
4422
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004423// Send a tap and respond, which should not cause an ANR.
4424TEST_F(InputDispatcherSingleWindowAnr, WhenTouchIsConsumed_NoAnr) {
4425 tapOnWindow();
4426 mWindow->consumeMotionDown();
4427 mWindow->consumeMotionUp();
4428 ASSERT_TRUE(mDispatcher->waitForIdle());
4429 mFakePolicy->assertNotifyAnrWasNotCalled();
4430}
4431
4432// Send a regular key and respond, which should not cause an ANR.
4433TEST_F(InputDispatcherSingleWindowAnr, WhenKeyIsConsumed_NoAnr) {
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004434 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004435 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
4436 ASSERT_TRUE(mDispatcher->waitForIdle());
4437 mFakePolicy->assertNotifyAnrWasNotCalled();
4438}
4439
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004440TEST_F(InputDispatcherSingleWindowAnr, WhenFocusedApplicationChanges_NoAnr) {
4441 mWindow->setFocusable(false);
4442 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4443 mWindow->consumeFocusEvent(false);
4444
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004445 InputEventInjectionResult result =
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004446 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004447 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
4448 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004449 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoue41c4512020-09-08 19:35:58 -05004450 // Key will not go to window because we have no focused window.
4451 // The 'no focused window' ANR timer should start instead.
4452
4453 // Now, the focused application goes away.
4454 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, nullptr);
4455 // The key should get dropped and there should be no ANR.
4456
4457 ASSERT_TRUE(mDispatcher->waitForIdle());
4458 mFakePolicy->assertNotifyAnrWasNotCalled();
4459}
4460
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004461// Send an event to the app and have the app not respond right away.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004462// When ANR is raised, policy will tell the dispatcher to cancel the events for that window.
4463// So InputDispatcher will enqueue ACTION_CANCEL event as well.
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004464TEST_F(InputDispatcherSingleWindowAnr, OnPointerDown_BasicAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004465 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004466 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4467 WINDOW_LOCATION));
4468
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004469 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent(); // ACTION_DOWN
4470 ASSERT_TRUE(sequenceNum);
4471 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004472 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004473
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004474 mWindow->finishEvent(*sequenceNum);
4475 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4476 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004477 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004478 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004479}
4480
4481// Send a key to the app and have the app not respond right away.
4482TEST_F(InputDispatcherSingleWindowAnr, OnKeyDown_BasicAnr) {
4483 // Inject a key, and don't respond - expect that ANR is called.
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004484 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDownNoRepeat(mDispatcher));
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004485 std::optional<uint32_t> sequenceNum = mWindow->receiveEvent();
4486 ASSERT_TRUE(sequenceNum);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004487 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004488 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakou4cb50ca2020-05-26 21:43:02 -07004489 ASSERT_TRUE(mDispatcher->waitForIdle());
4490}
4491
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004492// We have a focused application, but no focused window
4493TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004494 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004495 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4496 mWindow->consumeFocusEvent(false);
4497
4498 // taps on the window work as normal
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004499 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004500 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4501 WINDOW_LOCATION));
4502 ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
4503 mDispatcher->waitForIdle();
4504 mFakePolicy->assertNotifyAnrWasNotCalled();
4505
4506 // Once a focused event arrives, we get an ANR for this application
4507 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4508 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004509 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004510 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004511 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004512 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004513 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004514 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004515 ASSERT_TRUE(mDispatcher->waitForIdle());
4516}
4517
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004518/**
4519 * Make sure the stale key is dropped before causing an ANR. So even if there's no focused window,
4520 * there will not be an ANR.
4521 */
4522TEST_F(InputDispatcherSingleWindowAnr, StaleKeyEventDoesNotAnr) {
4523 mWindow->setFocusable(false);
4524 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4525 mWindow->consumeFocusEvent(false);
4526
4527 KeyEvent event;
4528 const nsecs_t eventTime = systemTime(SYSTEM_TIME_MONOTONIC) -
4529 std::chrono::nanoseconds(STALE_EVENT_TIMEOUT).count();
4530
4531 // Define a valid key down event that is stale (too old).
4532 event.initialize(InputEvent::nextId(), DEVICE_ID, AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_NONE,
4533 INVALID_HMAC, AKEY_EVENT_ACTION_DOWN, /* flags */ 0, AKEYCODE_A, KEY_A,
4534 AMETA_NONE, 1 /*repeatCount*/, eventTime, eventTime);
4535
4536 const int32_t policyFlags = POLICY_FLAG_FILTERED | POLICY_FLAG_PASS_TO_USER;
4537
4538 InputEventInjectionResult result =
Prabir Pradhan4df80f52022-04-05 18:33:16 +00004539 mDispatcher->injectInputEvent(&event, INJECTOR_PID, INJECTOR_UID,
Siarhei Vishniakou289e9242022-02-15 14:50:16 -08004540 InputEventInjectionSync::WAIT_FOR_RESULT,
4541 INJECT_EVENT_TIMEOUT, policyFlags);
4542 ASSERT_EQ(InputEventInjectionResult::FAILED, result)
4543 << "Injection should fail because the event is stale";
4544
4545 ASSERT_TRUE(mDispatcher->waitForIdle());
4546 mFakePolicy->assertNotifyAnrWasNotCalled();
4547 mWindow->assertNoEvents();
4548}
4549
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004550// We have a focused application, but no focused window
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004551// Make sure that we don't notify policy twice about the same ANR.
4552TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DoesNotSendDuplicateAnr) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004553 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004554 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4555 mWindow->consumeFocusEvent(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004556
4557 // Once a focused event arrives, we get an ANR for this application
4558 // We specify the injection timeout to be smaller than the application timeout, to ensure that
4559 // injection times out (instead of failing).
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004560 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004561 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08004562 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004563 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004564 const std::chrono::duration appTimeout =
4565 mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004566 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004567
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004568 std::this_thread::sleep_for(appTimeout);
4569 // ANR should not be raised again. It is up to policy to do that if it desires.
4570 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004571
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004572 // If we now get a focused window, the ANR should stop, but the policy handles that via
4573 // 'notifyFocusChanged' callback. This is implemented in the policy so we can't test it here.
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004574 ASSERT_TRUE(mDispatcher->waitForIdle());
4575}
4576
4577// We have a focused application, but no focused window
4578TEST_F(InputDispatcherSingleWindowAnr, NoFocusedWindow_DropsFocusedEvents) {
Vishnu Nair47074b82020-08-14 11:54:47 -07004579 mWindow->setFocusable(false);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004580 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4581 mWindow->consumeFocusEvent(false);
4582
4583 // Once a focused event arrives, we get an ANR for this application
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004584 const InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004585 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004586 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4587 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004588
4589 const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004590 mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004591
4592 // Future focused events get dropped right away
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004593 ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004594 ASSERT_TRUE(mDispatcher->waitForIdle());
4595 mWindow->assertNoEvents();
4596}
4597
4598/**
4599 * Ensure that the implementation is valid. Since we are using multiset to keep track of the
4600 * ANR timeouts, we are allowing entries with identical timestamps in the same connection.
4601 * If we process 1 of the events, but ANR on the second event with the same timestamp,
4602 * the ANR mechanism should still work.
4603 *
4604 * In this test, we are injecting DOWN and UP events with the same timestamps, and acknowledging the
4605 * DOWN event, while not responding on the second one.
4606 */
4607TEST_F(InputDispatcherSingleWindowAnr, Anr_HandlesEventsWithIdenticalTimestamps) {
4608 nsecs_t currentTime = systemTime(SYSTEM_TIME_MONOTONIC);
4609 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
4610 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4611 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4612 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004613 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004614
4615 // Now send ACTION_UP, with identical timestamp
4616 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
4617 ADISPLAY_ID_DEFAULT, WINDOW_LOCATION,
4618 {AMOTION_EVENT_INVALID_CURSOR_POSITION,
4619 AMOTION_EVENT_INVALID_CURSOR_POSITION},
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004620 500ms, InputEventInjectionSync::WAIT_FOR_RESULT, currentTime);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004621
4622 // We have now sent down and up. Let's consume first event and then ANR on the second.
4623 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4624 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004625 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004626}
4627
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004628// A spy window can receive an ANR
4629TEST_F(InputDispatcherSingleWindowAnr, SpyWindowAnr) {
4630 sp<FakeWindowHandle> spy = addSpyWindow();
4631
4632 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4633 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4634 WINDOW_LOCATION));
4635 mWindow->consumeMotionDown();
4636
4637 std::optional<uint32_t> sequenceNum = spy->receiveEvent(); // ACTION_DOWN
4638 ASSERT_TRUE(sequenceNum);
4639 const std::chrono::duration timeout = spy->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004640 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, spy);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004641
4642 spy->finishEvent(*sequenceNum);
4643 spy->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL, ADISPLAY_ID_DEFAULT,
4644 0 /*flags*/);
4645 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004646 mFakePolicy->assertNotifyWindowResponsiveWasCalled(spy->getToken(), mWindow->getPid());
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004647}
4648
4649// If an app is not responding to a key event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004650// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004651TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnKey) {
4652 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004653
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004654 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4655 injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004656 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004657 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher, ADISPLAY_ID_DEFAULT));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004658
4659 // Stuck on the ACTION_UP
4660 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004661 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004662
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004663 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004664 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004665 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4666 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004667
4668 mWindow->consumeKeyUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4669 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004670 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004671 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004672 spy->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004673}
4674
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004675// If an app is not responding to a motion event, spy windows should continue to receive
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004676// new motion events
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004677TEST_F(InputDispatcherSingleWindowAnr, SpyWindowReceivesEventsDuringAppAnrOnMotion) {
4678 sp<FakeWindowHandle> spy = addSpyWindow();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004679
4680 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004681 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4682 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004683
4684 mWindow->consumeMotionDown();
4685 // Stuck on the ACTION_UP
4686 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004687 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004688
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004689 // New tap will go to the spy window, but not to the window
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004690 tapOnWindow();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004691 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4692 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004693
4694 mWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT); // still the previous motion
4695 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004696 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004697 mWindow->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004698 spy->assertNoEvents();
4699}
4700
4701TEST_F(InputDispatcherSingleWindowAnr, UnresponsiveMonitorAnr) {
4702 mDispatcher->setMonitorDispatchingTimeoutForTest(30ms);
4703
4704 FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "M_1", ADISPLAY_ID_DEFAULT);
4705
4706 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
4707 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4708 WINDOW_LOCATION));
4709
4710 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
4711 const std::optional<uint32_t> consumeSeq = monitor.receiveEvent();
4712 ASSERT_TRUE(consumeSeq);
4713
Prabir Pradhanedd96402022-02-15 01:46:16 -08004714 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(30ms, monitor.getToken(), MONITOR_PID);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08004715
4716 monitor.finishEvent(*consumeSeq);
4717 monitor.consumeMotionCancel(ADISPLAY_ID_DEFAULT);
4718
4719 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004720 mFakePolicy->assertNotifyWindowResponsiveWasCalled(monitor.getToken(), MONITOR_PID);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004721}
4722
4723// If a window is unresponsive, then you get anr. if the window later catches up and starts to
4724// process events, you don't get an anr. When the window later becomes unresponsive again, you
4725// get an ANR again.
4726// 1. tap -> block on ACTION_UP -> receive ANR
4727// 2. consume all pending events (= queue becomes healthy again)
4728// 3. tap again -> block on ACTION_UP again -> receive ANR second time
4729TEST_F(InputDispatcherSingleWindowAnr, SameWindow_CanReceiveAnrTwice) {
4730 tapOnWindow();
4731
4732 mWindow->consumeMotionDown();
4733 // Block on ACTION_UP
4734 const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004735 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004736 mWindow->consumeMotionUp(); // Now the connection should be healthy again
4737 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004738 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004739 mWindow->assertNoEvents();
4740
4741 tapOnWindow();
4742 mWindow->consumeMotionDown();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004743 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004744 mWindow->consumeMotionUp();
4745
4746 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004747 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004748 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004749 mWindow->assertNoEvents();
4750}
4751
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004752// If a connection remains unresponsive for a while, make sure policy is only notified once about
4753// it.
4754TEST_F(InputDispatcherSingleWindowAnr, Policy_DoesNotGetDuplicateAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004755 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004756 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4757 WINDOW_LOCATION));
4758
4759 const std::chrono::duration windowTimeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004760 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(windowTimeout, mWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004761 std::this_thread::sleep_for(windowTimeout);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004762 // 'notifyConnectionUnresponsive' should only be called once per connection
4763 mFakePolicy->assertNotifyAnrWasNotCalled();
4764 // When the ANR happened, dispatcher should abort the current event stream via ACTION_CANCEL
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004765 mWindow->consumeMotionDown();
4766 mWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_CANCEL,
4767 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4768 mWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004769 mDispatcher->waitForIdle();
Prabir Pradhanedd96402022-02-15 01:46:16 -08004770 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mWindow->getToken(), mWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004771 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004772}
4773
4774/**
4775 * If a window is processing a motion event, and then a key event comes in, the key event should
4776 * not to to the focused window until the motion is processed.
4777 *
4778 * Warning!!!
4779 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
4780 * and the injection timeout that we specify when injecting the key.
4781 * We must have the injection timeout (10ms) be smaller than
4782 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
4783 *
4784 * If that value changes, this test should also change.
4785 */
4786TEST_F(InputDispatcherSingleWindowAnr, Key_StaysPendingWhileMotionIsProcessed) {
4787 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4788 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4789
4790 tapOnWindow();
4791 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4792 ASSERT_TRUE(downSequenceNum);
4793 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4794 ASSERT_TRUE(upSequenceNum);
4795 // Don't finish the events yet, and send a key
4796 // Injection will "succeed" because we will eventually give up and send the key to the focused
4797 // window even if motions are still being processed. But because the injection timeout is short,
4798 // we will receive INJECTION_TIMED_OUT as the result.
4799
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004800 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004801 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004802 InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
4803 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004804 // Key will not be sent to the window, yet, because the window is still processing events
4805 // and the key remains pending, waiting for the touch events to be processed
4806 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4807 ASSERT_FALSE(keySequenceNum);
4808
4809 std::this_thread::sleep_for(500ms);
4810 // if we wait long enough though, dispatcher will give up, and still send the key
4811 // to the focused window, even though we have not yet finished the motion event
4812 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
4813 mWindow->finishEvent(*downSequenceNum);
4814 mWindow->finishEvent(*upSequenceNum);
4815}
4816
4817/**
4818 * If a window is processing a motion event, and then a key event comes in, the key event should
4819 * not go to the focused window until the motion is processed.
4820 * If then a new motion comes in, then the pending key event should be going to the currently
4821 * focused window right away.
4822 */
4823TEST_F(InputDispatcherSingleWindowAnr,
4824 PendingKey_IsDroppedWhileMotionIsProcessedAndNewTouchComesIn) {
4825 mWindow->setDispatchingTimeout(2s); // Set a long ANR timeout to prevent it from triggering
4826 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
4827
4828 tapOnWindow();
4829 std::optional<uint32_t> downSequenceNum = mWindow->receiveEvent();
4830 ASSERT_TRUE(downSequenceNum);
4831 std::optional<uint32_t> upSequenceNum = mWindow->receiveEvent();
4832 ASSERT_TRUE(upSequenceNum);
4833 // Don't finish the events yet, and send a key
4834 // Injection is async, so it will succeed
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004835 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004836 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004837 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004838 // At this point, key is still pending, and should not be sent to the application yet.
4839 std::optional<uint32_t> keySequenceNum = mWindow->receiveEvent();
4840 ASSERT_FALSE(keySequenceNum);
4841
4842 // Now tap down again. It should cause the pending key to go to the focused window right away.
4843 tapOnWindow();
4844 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT); // it doesn't matter that we haven't ack'd
4845 // the other events yet. We can finish events in any order.
4846 mWindow->finishEvent(*downSequenceNum); // first tap's ACTION_DOWN
4847 mWindow->finishEvent(*upSequenceNum); // first tap's ACTION_UP
4848 mWindow->consumeMotionDown();
4849 mWindow->consumeMotionUp();
4850 mWindow->assertNoEvents();
4851}
4852
4853class InputDispatcherMultiWindowAnr : public InputDispatcherTest {
4854 virtual void SetUp() override {
4855 InputDispatcherTest::SetUp();
4856
Chris Yea209fde2020-07-22 13:54:51 -07004857 mApplication = std::make_shared<FakeApplicationHandle>();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004858 mApplication->setDispatchingTimeout(10ms);
4859 mUnfocusedWindow =
4860 new FakeWindowHandle(mApplication, mDispatcher, "Unfocused", ADISPLAY_ID_DEFAULT);
4861 mUnfocusedWindow->setFrame(Rect(0, 0, 30, 30));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004862 // Adding FLAG_WATCH_OUTSIDE_TOUCH to receive ACTION_OUTSIDE when another window is tapped
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08004863 mUnfocusedWindow->setWatchOutsideTouch(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004864
4865 mFocusedWindow =
4866 new FakeWindowHandle(mApplication, mDispatcher, "Focused", ADISPLAY_ID_DEFAULT);
Siarhei Vishniakoua7d36fd2020-06-30 19:32:39 -05004867 mFocusedWindow->setDispatchingTimeout(30ms);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004868 mFocusedWindow->setFrame(Rect(50, 50, 100, 100));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004869
4870 // Set focused application.
4871 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApplication);
Vishnu Nair47074b82020-08-14 11:54:47 -07004872 mFocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004873
4874 // Expect one focus window exist in display.
4875 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07004876 setFocusedWindow(mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004877 mFocusedWindow->consumeFocusEvent(true);
4878 }
4879
4880 virtual void TearDown() override {
4881 InputDispatcherTest::TearDown();
4882
4883 mUnfocusedWindow.clear();
4884 mFocusedWindow.clear();
4885 }
4886
4887protected:
Chris Yea209fde2020-07-22 13:54:51 -07004888 std::shared_ptr<FakeApplicationHandle> mApplication;
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004889 sp<FakeWindowHandle> mUnfocusedWindow;
4890 sp<FakeWindowHandle> mFocusedWindow;
4891 static constexpr PointF UNFOCUSED_WINDOW_LOCATION = {20, 20};
4892 static constexpr PointF FOCUSED_WINDOW_LOCATION = {75, 75};
4893 static constexpr PointF LOCATION_OUTSIDE_ALL_WINDOWS = {40, 40};
4894
4895 void tapOnFocusedWindow() { tap(FOCUSED_WINDOW_LOCATION); }
4896
4897 void tapOnUnfocusedWindow() { tap(UNFOCUSED_WINDOW_LOCATION); }
4898
4899private:
4900 void tap(const PointF& location) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004901 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004902 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4903 location));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004904 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004905 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4906 location));
4907 }
4908};
4909
4910// If we have 2 windows that are both unresponsive, the one with the shortest timeout
4911// should be ANR'd first.
4912TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsive) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004913 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004914 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4915 FOCUSED_WINDOW_LOCATION))
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004916 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004917 mFocusedWindow->consumeMotionDown();
4918 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4919 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4920 // We consumed all events, so no ANR
4921 ASSERT_TRUE(mDispatcher->waitForIdle());
4922 mFakePolicy->assertNotifyAnrWasNotCalled();
4923
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08004924 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004925 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
4926 FOCUSED_WINDOW_LOCATION));
4927 std::optional<uint32_t> unfocusedSequenceNum = mUnfocusedWindow->receiveEvent();
4928 ASSERT_TRUE(unfocusedSequenceNum);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004929
4930 const std::chrono::duration timeout =
4931 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08004932 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004933 // Because we injected two DOWN events in a row, CANCEL is enqueued for the first event
4934 // sequence to make it consistent
4935 mFocusedWindow->consumeMotionCancel();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004936 mUnfocusedWindow->finishEvent(*unfocusedSequenceNum);
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004937 mFocusedWindow->consumeMotionDown();
4938 // This cancel is generated because the connection was unresponsive
4939 mFocusedWindow->consumeMotionCancel();
4940 mFocusedWindow->assertNoEvents();
4941 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004942 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08004943 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
4944 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004945 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004946}
4947
4948// If we have 2 windows with identical timeouts that are both unresponsive,
4949// it doesn't matter which order they should have ANR.
4950// But we should receive ANR for both.
4951TEST_F(InputDispatcherMultiWindowAnr, TwoWindows_BothUnresponsiveWithSameTimeout) {
4952 // Set the timeout for unfocused window to match the focused window
4953 mUnfocusedWindow->setDispatchingTimeout(10ms);
4954 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
4955
4956 tapOnFocusedWindow();
4957 // we should have ACTION_DOWN/ACTION_UP on focused window and ACTION_OUTSIDE on unfocused window
Prabir Pradhanedd96402022-02-15 01:46:16 -08004958 sp<IBinder> anrConnectionToken1, anrConnectionToken2;
4959 ASSERT_NO_FATAL_FAILURE(anrConnectionToken1 = mFakePolicy->getUnresponsiveWindowToken(10ms));
4960 ASSERT_NO_FATAL_FAILURE(anrConnectionToken2 = mFakePolicy->getUnresponsiveWindowToken(0ms));
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004961
4962 // We don't know which window will ANR first. But both of them should happen eventually.
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004963 ASSERT_TRUE(mFocusedWindow->getToken() == anrConnectionToken1 ||
4964 mFocusedWindow->getToken() == anrConnectionToken2);
4965 ASSERT_TRUE(mUnfocusedWindow->getToken() == anrConnectionToken1 ||
4966 mUnfocusedWindow->getToken() == anrConnectionToken2);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004967
4968 ASSERT_TRUE(mDispatcher->waitForIdle());
4969 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004970
4971 mFocusedWindow->consumeMotionDown();
4972 mFocusedWindow->consumeMotionUp();
4973 mUnfocusedWindow->consumeMotionOutside();
4974
Prabir Pradhanedd96402022-02-15 01:46:16 -08004975 sp<IBinder> responsiveToken1, responsiveToken2;
4976 ASSERT_NO_FATAL_FAILURE(responsiveToken1 = mFakePolicy->getResponsiveWindowToken());
4977 ASSERT_NO_FATAL_FAILURE(responsiveToken2 = mFakePolicy->getResponsiveWindowToken());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05004978
4979 // Both applications should be marked as responsive, in any order
4980 ASSERT_TRUE(mFocusedWindow->getToken() == responsiveToken1 ||
4981 mFocusedWindow->getToken() == responsiveToken2);
4982 ASSERT_TRUE(mUnfocusedWindow->getToken() == responsiveToken1 ||
4983 mUnfocusedWindow->getToken() == responsiveToken2);
4984 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07004985}
4986
4987// If a window is already not responding, the second tap on the same window should be ignored.
4988// We should also log an error to account for the dropped event (not tested here).
4989// At the same time, FLAG_WATCH_OUTSIDE_TOUCH targets should not receive any events.
4990TEST_F(InputDispatcherMultiWindowAnr, DuringAnr_SecondTapIsIgnored) {
4991 tapOnFocusedWindow();
4992 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
4993 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
4994 // Receive the events, but don't respond
4995 std::optional<uint32_t> downEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_DOWN
4996 ASSERT_TRUE(downEventSequenceNum);
4997 std::optional<uint32_t> upEventSequenceNum = mFocusedWindow->receiveEvent(); // ACTION_UP
4998 ASSERT_TRUE(upEventSequenceNum);
4999 const std::chrono::duration timeout =
5000 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005001 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005002
5003 // Tap once again
5004 // We cannot use "tapOnFocusedWindow" because it asserts the injection result to be success
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005005 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005006 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5007 FOCUSED_WINDOW_LOCATION));
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005008 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005009 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5010 FOCUSED_WINDOW_LOCATION));
5011 // Unfocused window does not receive ACTION_OUTSIDE because the tapped window is not a
5012 // valid touch target
5013 mUnfocusedWindow->assertNoEvents();
5014
5015 // Consume the first tap
5016 mFocusedWindow->finishEvent(*downEventSequenceNum);
5017 mFocusedWindow->finishEvent(*upEventSequenceNum);
5018 ASSERT_TRUE(mDispatcher->waitForIdle());
5019 // The second tap did not go to the focused window
5020 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005021 // Since all events are finished, connection should be deemed healthy again
Prabir Pradhanedd96402022-02-15 01:46:16 -08005022 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5023 mFocusedWindow->getPid());
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005024 mFakePolicy->assertNotifyAnrWasNotCalled();
5025}
5026
5027// If you tap outside of all windows, there will not be ANR
5028TEST_F(InputDispatcherMultiWindowAnr, TapOutsideAllWindows_DoesNotAnr) {
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005029 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005030 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5031 LOCATION_OUTSIDE_ALL_WINDOWS));
5032 ASSERT_TRUE(mDispatcher->waitForIdle());
5033 mFakePolicy->assertNotifyAnrWasNotCalled();
5034}
5035
5036// Since the focused window is paused, tapping on it should not produce any events
5037TEST_F(InputDispatcherMultiWindowAnr, Window_CanBePaused) {
5038 mFocusedWindow->setPaused(true);
5039 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
5040
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005041 ASSERT_EQ(InputEventInjectionResult::FAILED,
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005042 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5043 FOCUSED_WINDOW_LOCATION));
5044
5045 std::this_thread::sleep_for(mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT));
5046 ASSERT_TRUE(mDispatcher->waitForIdle());
5047 // Should not ANR because the window is paused, and touches shouldn't go to it
5048 mFakePolicy->assertNotifyAnrWasNotCalled();
5049
5050 mFocusedWindow->assertNoEvents();
5051 mUnfocusedWindow->assertNoEvents();
5052}
5053
5054/**
5055 * If a window is processing a motion event, and then a key event comes in, the key event should
5056 * not to to the focused window until the motion is processed.
5057 * If a different window becomes focused at this time, the key should go to that window instead.
5058 *
5059 * Warning!!!
5060 * This test depends on the value of android::inputdispatcher::KEY_WAITING_FOR_MOTION_TIMEOUT
5061 * and the injection timeout that we specify when injecting the key.
5062 * We must have the injection timeout (10ms) be smaller than
5063 * KEY_WAITING_FOR_MOTION_TIMEOUT (currently 500ms).
5064 *
5065 * If that value changes, this test should also change.
5066 */
5067TEST_F(InputDispatcherMultiWindowAnr, PendingKey_GoesToNewlyFocusedWindow) {
5068 // Set a long ANR timeout to prevent it from triggering
5069 mFocusedWindow->setDispatchingTimeout(2s);
5070 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5071
5072 tapOnUnfocusedWindow();
5073 std::optional<uint32_t> downSequenceNum = mUnfocusedWindow->receiveEvent();
5074 ASSERT_TRUE(downSequenceNum);
5075 std::optional<uint32_t> upSequenceNum = mUnfocusedWindow->receiveEvent();
5076 ASSERT_TRUE(upSequenceNum);
5077 // Don't finish the events yet, and send a key
5078 // Injection will succeed because we will eventually give up and send the key to the focused
5079 // window even if motions are still being processed.
5080
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005081 InputEventInjectionResult result =
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005082 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005083 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/);
5084 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005085 // Key will not be sent to the window, yet, because the window is still processing events
5086 // and the key remains pending, waiting for the touch events to be processed
5087 std::optional<uint32_t> keySequenceNum = mFocusedWindow->receiveEvent();
5088 ASSERT_FALSE(keySequenceNum);
5089
5090 // Switch the focus to the "unfocused" window that we tapped. Expect the key to go there
Vishnu Nair47074b82020-08-14 11:54:47 -07005091 mFocusedWindow->setFocusable(false);
5092 mUnfocusedWindow->setFocusable(true);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005093 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
Vishnu Nair958da932020-08-21 17:12:37 -07005094 setFocusedWindow(mUnfocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005095
5096 // Focus events should precede the key events
5097 mUnfocusedWindow->consumeFocusEvent(true);
5098 mFocusedWindow->consumeFocusEvent(false);
5099
5100 // Finish the tap events, which should unblock dispatcher
5101 mUnfocusedWindow->finishEvent(*downSequenceNum);
5102 mUnfocusedWindow->finishEvent(*upSequenceNum);
5103
5104 // Now that all queues are cleared and no backlog in the connections, the key event
5105 // can finally go to the newly focused "mUnfocusedWindow".
5106 mUnfocusedWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5107 mFocusedWindow->assertNoEvents();
5108 mUnfocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005109 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005110}
5111
5112// When the touch stream is split across 2 windows, and one of them does not respond,
5113// then ANR should be raised and the touch should be canceled for the unresponsive window.
5114// The other window should not be affected by that.
5115TEST_F(InputDispatcherMultiWindowAnr, SplitTouch_SingleWindowAnr) {
5116 // Touch Window 1
5117 NotifyMotionArgs motionArgs =
5118 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5119 ADISPLAY_ID_DEFAULT, {FOCUSED_WINDOW_LOCATION});
5120 mDispatcher->notifyMotion(&motionArgs);
5121 mUnfocusedWindow->consumeEvent(AINPUT_EVENT_TYPE_MOTION, AMOTION_EVENT_ACTION_OUTSIDE,
5122 ADISPLAY_ID_DEFAULT, 0 /*flags*/);
5123
5124 // Touch Window 2
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08005125 motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5126 {FOCUSED_WINDOW_LOCATION, UNFOCUSED_WINDOW_LOCATION});
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005127 mDispatcher->notifyMotion(&motionArgs);
5128
5129 const std::chrono::duration timeout =
5130 mFocusedWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
Prabir Pradhanedd96402022-02-15 01:46:16 -08005131 mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mFocusedWindow);
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005132
5133 mUnfocusedWindow->consumeMotionDown();
5134 mFocusedWindow->consumeMotionDown();
5135 // Focused window may or may not receive ACTION_MOVE
5136 // But it should definitely receive ACTION_CANCEL due to the ANR
5137 InputEvent* event;
5138 std::optional<int32_t> moveOrCancelSequenceNum = mFocusedWindow->receiveEvent(&event);
5139 ASSERT_TRUE(moveOrCancelSequenceNum);
5140 mFocusedWindow->finishEvent(*moveOrCancelSequenceNum);
5141 ASSERT_NE(nullptr, event);
5142 ASSERT_EQ(event->getType(), AINPUT_EVENT_TYPE_MOTION);
5143 MotionEvent& motionEvent = static_cast<MotionEvent&>(*event);
5144 if (motionEvent.getAction() == AMOTION_EVENT_ACTION_MOVE) {
5145 mFocusedWindow->consumeMotionCancel();
5146 } else {
5147 ASSERT_EQ(AMOTION_EVENT_ACTION_CANCEL, motionEvent.getAction());
5148 }
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005149 ASSERT_TRUE(mDispatcher->waitForIdle());
Prabir Pradhanedd96402022-02-15 01:46:16 -08005150 mFakePolicy->assertNotifyWindowResponsiveWasCalled(mFocusedWindow->getToken(),
5151 mFocusedWindow->getPid());
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005152
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005153 mUnfocusedWindow->assertNoEvents();
5154 mFocusedWindow->assertNoEvents();
Siarhei Vishniakou234129c2020-10-22 22:28:12 -05005155 mFakePolicy->assertNotifyAnrWasNotCalled();
Siarhei Vishniakoud44dddf2020-03-25 16:16:40 -07005156}
5157
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005158/**
5159 * If we have no focused window, and a key comes in, we start the ANR timer.
5160 * The focused application should add a focused window before the timer runs out to prevent ANR.
5161 *
5162 * If the user touches another application during this time, the key should be dropped.
5163 * Next, if a new focused window comes in, without toggling the focused application,
5164 * then no ANR should occur.
5165 *
5166 * Normally, we would expect the new focused window to be accompanied by 'setFocusedApplication',
5167 * but in some cases the policy may not update the focused application.
5168 */
5169TEST_F(InputDispatcherMultiWindowAnr, FocusedWindowWithoutSetFocusedApplication_NoAnr) {
5170 std::shared_ptr<FakeApplicationHandle> focusedApplication =
5171 std::make_shared<FakeApplicationHandle>();
5172 focusedApplication->setDispatchingTimeout(60ms);
5173 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, focusedApplication);
5174 // The application that owns 'mFocusedWindow' and 'mUnfocusedWindow' is not focused.
5175 mFocusedWindow->setFocusable(false);
5176
5177 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5178 mFocusedWindow->consumeFocusEvent(false);
5179
5180 // Send a key. The ANR timer should start because there is no focused window.
5181 // 'focusedApplication' will get blamed if this timer completes.
5182 // Key will not be sent anywhere because we have no focused window. It will remain pending.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005183 InputEventInjectionResult result =
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005184 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /*repeatCount*/, ADISPLAY_ID_DEFAULT,
Prabir Pradhan93f342c2021-03-11 15:05:30 -08005185 InputEventInjectionSync::NONE, 10ms /*injectionTimeout*/,
5186 false /* allowKeyRepeat */);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005187 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, result);
Siarhei Vishniakouf56b2692020-09-08 19:43:33 -05005188
5189 // Wait until dispatcher starts the "no focused window" timer. If we don't wait here,
5190 // then the injected touches won't cause the focused event to get dropped.
5191 // The dispatcher only checks for whether the queue should be pruned upon queueing.
5192 // If we inject the touch right away and the ANR timer hasn't started, the touch event would
5193 // simply be added to the queue without 'shouldPruneInboundQueueLocked' returning 'true'.
5194 // For this test, it means that the key would get delivered to the window once it becomes
5195 // focused.
5196 std::this_thread::sleep_for(10ms);
5197
5198 // Touch unfocused window. This should force the pending key to get dropped.
5199 NotifyMotionArgs motionArgs =
5200 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5201 ADISPLAY_ID_DEFAULT, {UNFOCUSED_WINDOW_LOCATION});
5202 mDispatcher->notifyMotion(&motionArgs);
5203
5204 // We do not consume the motion right away, because that would require dispatcher to first
5205 // process (== drop) the key event, and by that time, ANR will be raised.
5206 // Set the focused window first.
5207 mFocusedWindow->setFocusable(true);
5208 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mFocusedWindow, mUnfocusedWindow}}});
5209 setFocusedWindow(mFocusedWindow);
5210 mFocusedWindow->consumeFocusEvent(true);
5211 // We do not call "setFocusedApplication" here, even though the newly focused window belongs
5212 // to another application. This could be a bug / behaviour in the policy.
5213
5214 mUnfocusedWindow->consumeMotionDown();
5215
5216 ASSERT_TRUE(mDispatcher->waitForIdle());
5217 // Should not ANR because we actually have a focused window. It was just added too slowly.
5218 ASSERT_NO_FATAL_FAILURE(mFakePolicy->assertNotifyAnrWasNotCalled());
5219}
5220
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005221// These tests ensure we cannot send touch events to a window that's positioned behind a window
5222// that has feature NO_INPUT_CHANNEL.
5223// Layout:
5224// Top (closest to user)
5225// mNoInputWindow (above all windows)
5226// mBottomWindow
5227// Bottom (furthest from user)
5228class InputDispatcherMultiWindowOcclusionTests : public InputDispatcherTest {
5229 virtual void SetUp() override {
5230 InputDispatcherTest::SetUp();
5231
5232 mApplication = std::make_shared<FakeApplicationHandle>();
5233 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5234 "Window without input channel", ADISPLAY_ID_DEFAULT,
5235 std::make_optional<sp<IBinder>>(nullptr) /*token*/);
5236
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005237 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005238 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5239 // It's perfectly valid for this window to not have an associated input channel
5240
5241 mBottomWindow = new FakeWindowHandle(mApplication, mDispatcher, "Bottom window",
5242 ADISPLAY_ID_DEFAULT);
5243 mBottomWindow->setFrame(Rect(0, 0, 100, 100));
5244
5245 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5246 }
5247
5248protected:
5249 std::shared_ptr<FakeApplicationHandle> mApplication;
5250 sp<FakeWindowHandle> mNoInputWindow;
5251 sp<FakeWindowHandle> mBottomWindow;
5252};
5253
5254TEST_F(InputDispatcherMultiWindowOcclusionTests, NoInputChannelFeature_DropsTouches) {
5255 PointF touchedPoint = {10, 10};
5256
5257 NotifyMotionArgs motionArgs =
5258 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5259 ADISPLAY_ID_DEFAULT, {touchedPoint});
5260 mDispatcher->notifyMotion(&motionArgs);
5261
5262 mNoInputWindow->assertNoEvents();
5263 // Even though the window 'mNoInputWindow' positioned above 'mBottomWindow' does not have
5264 // an input channel, it is not marked as FLAG_NOT_TOUCHABLE,
5265 // and therefore should prevent mBottomWindow from receiving touches
5266 mBottomWindow->assertNoEvents();
5267}
5268
5269/**
5270 * If a window has feature NO_INPUT_CHANNEL, and somehow (by mistake) still has an input channel,
5271 * ensure that this window does not receive any touches, and blocks touches to windows underneath.
5272 */
5273TEST_F(InputDispatcherMultiWindowOcclusionTests,
5274 NoInputChannelFeature_DropsTouchesWithValidChannel) {
5275 mNoInputWindow = new FakeWindowHandle(mApplication, mDispatcher,
5276 "Window with input channel and NO_INPUT_CHANNEL",
5277 ADISPLAY_ID_DEFAULT);
5278
Prabir Pradhan51e7db02022-02-07 06:02:57 -08005279 mNoInputWindow->setNoInputChannel(true);
Siarhei Vishniakoua2862a02020-07-20 16:36:46 -05005280 mNoInputWindow->setFrame(Rect(0, 0, 100, 100));
5281 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mNoInputWindow, mBottomWindow}}});
5282
5283 PointF touchedPoint = {10, 10};
5284
5285 NotifyMotionArgs motionArgs =
5286 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5287 ADISPLAY_ID_DEFAULT, {touchedPoint});
5288 mDispatcher->notifyMotion(&motionArgs);
5289
5290 mNoInputWindow->assertNoEvents();
5291 mBottomWindow->assertNoEvents();
5292}
5293
Vishnu Nair958da932020-08-21 17:12:37 -07005294class InputDispatcherMirrorWindowFocusTests : public InputDispatcherTest {
5295protected:
5296 std::shared_ptr<FakeApplicationHandle> mApp;
5297 sp<FakeWindowHandle> mWindow;
5298 sp<FakeWindowHandle> mMirror;
5299
5300 virtual void SetUp() override {
5301 InputDispatcherTest::SetUp();
5302 mApp = std::make_shared<FakeApplicationHandle>();
5303 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5304 mMirror = new FakeWindowHandle(mApp, mDispatcher, "TestWindowMirror", ADISPLAY_ID_DEFAULT,
5305 mWindow->getToken());
5306 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5307 mWindow->setFocusable(true);
5308 mMirror->setFocusable(true);
5309 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5310 }
5311};
5312
5313TEST_F(InputDispatcherMirrorWindowFocusTests, CanGetFocus) {
5314 // Request focus on a mirrored window
5315 setFocusedWindow(mMirror);
5316
5317 // window gets focused
5318 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005319 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5320 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005321 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
5322}
5323
5324// A focused & mirrored window remains focused only if the window and its mirror are both
5325// focusable.
5326TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAllWindowsFocusable) {
5327 setFocusedWindow(mMirror);
5328
5329 // window gets focused
5330 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005331 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5332 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005333 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005334 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5335 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005336 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5337
5338 mMirror->setFocusable(false);
5339 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5340
5341 // window loses focus since one of the windows associated with the token in not focusable
5342 mWindow->consumeFocusEvent(false);
5343
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005344 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5345 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005346 mWindow->assertNoEvents();
5347}
5348
5349// A focused & mirrored window remains focused until the window and its mirror both become
5350// invisible.
5351TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedIfAnyWindowVisible) {
5352 setFocusedWindow(mMirror);
5353
5354 // window gets focused
5355 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005356 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5357 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005358 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005359 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5360 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005361 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5362
5363 mMirror->setVisible(false);
5364 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5365
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005366 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5367 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005368 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005369 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5370 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005371 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5372
5373 mWindow->setVisible(false);
5374 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5375
5376 // window loses focus only after all windows associated with the token become invisible.
5377 mWindow->consumeFocusEvent(false);
5378
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005379 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5380 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005381 mWindow->assertNoEvents();
5382}
5383
5384// A focused & mirrored window remains focused until both windows are removed.
5385TEST_F(InputDispatcherMirrorWindowFocusTests, FocusedWhileWindowsAlive) {
5386 setFocusedWindow(mMirror);
5387
5388 // window gets focused
5389 mWindow->consumeFocusEvent(true);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005390 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5391 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005392 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005393 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5394 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005395 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5396
5397 // single window is removed but the window token remains focused
5398 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mMirror}}});
5399
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005400 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
5401 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005402 mWindow->consumeKeyDown(ADISPLAY_ID_NONE);
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005403 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
5404 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
Vishnu Nair958da932020-08-21 17:12:37 -07005405 mWindow->consumeKeyUp(ADISPLAY_ID_NONE);
5406
5407 // Both windows are removed
5408 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {}}});
5409 mWindow->consumeFocusEvent(false);
5410
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005411 ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, injectKeyDown(mDispatcher))
5412 << "Inject key event should return InputEventInjectionResult::TIMED_OUT";
Vishnu Nair958da932020-08-21 17:12:37 -07005413 mWindow->assertNoEvents();
5414}
5415
5416// Focus request can be pending until one window becomes visible.
5417TEST_F(InputDispatcherMirrorWindowFocusTests, DeferFocusWhenInvisible) {
5418 // Request focus on an invisible mirror.
5419 mWindow->setVisible(false);
5420 mMirror->setVisible(false);
5421 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5422 setFocusedWindow(mMirror);
5423
5424 // Injected key goes to pending queue.
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005425 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Vishnu Nair958da932020-08-21 17:12:37 -07005426 injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */,
Siarhei Vishniakouae6229e2019-12-30 16:23:19 -08005427 ADISPLAY_ID_DEFAULT, InputEventInjectionSync::NONE));
Vishnu Nair958da932020-08-21 17:12:37 -07005428
5429 mMirror->setVisible(true);
5430 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mMirror}}});
5431
5432 // window gets focused
5433 mWindow->consumeFocusEvent(true);
5434 // window gets the pending key event
5435 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
5436}
Prabir Pradhan99987712020-11-10 18:43:05 -08005437
5438class InputDispatcherPointerCaptureTests : public InputDispatcherTest {
5439protected:
5440 std::shared_ptr<FakeApplicationHandle> mApp;
5441 sp<FakeWindowHandle> mWindow;
5442 sp<FakeWindowHandle> mSecondWindow;
5443
5444 void SetUp() override {
5445 InputDispatcherTest::SetUp();
5446 mApp = std::make_shared<FakeApplicationHandle>();
5447 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5448 mWindow->setFocusable(true);
5449 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5450 mSecondWindow->setFocusable(true);
5451
5452 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5453 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5454
5455 setFocusedWindow(mWindow);
5456 mWindow->consumeFocusEvent(true);
5457 }
5458
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005459 void notifyPointerCaptureChanged(const PointerCaptureRequest& request) {
5460 const NotifyPointerCaptureChangedArgs args = generatePointerCaptureChangedArgs(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005461 mDispatcher->notifyPointerCaptureChanged(&args);
5462 }
5463
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005464 PointerCaptureRequest requestAndVerifyPointerCapture(const sp<FakeWindowHandle>& window,
5465 bool enabled) {
Prabir Pradhan99987712020-11-10 18:43:05 -08005466 mDispatcher->requestPointerCapture(window->getToken(), enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005467 auto request = mFakePolicy->assertSetPointerCaptureCalled(enabled);
5468 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005469 window->consumeCaptureEvent(enabled);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005470 return request;
Prabir Pradhan99987712020-11-10 18:43:05 -08005471 }
5472};
5473
5474TEST_F(InputDispatcherPointerCaptureTests, EnablePointerCaptureWhenFocused) {
5475 // Ensure that capture cannot be obtained for unfocused windows.
5476 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
5477 mFakePolicy->assertSetPointerCaptureNotCalled();
5478 mSecondWindow->assertNoEvents();
5479
5480 // Ensure that capture can be enabled from the focus window.
5481 requestAndVerifyPointerCapture(mWindow, true);
5482
5483 // Ensure that capture cannot be disabled from a window that does not have capture.
5484 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), false);
5485 mFakePolicy->assertSetPointerCaptureNotCalled();
5486
5487 // Ensure that capture can be disabled from the window with capture.
5488 requestAndVerifyPointerCapture(mWindow, false);
5489}
5490
5491TEST_F(InputDispatcherPointerCaptureTests, DisablesPointerCaptureAfterWindowLosesFocus) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005492 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005493
5494 setFocusedWindow(mSecondWindow);
5495
5496 // Ensure that the capture disabled event was sent first.
5497 mWindow->consumeCaptureEvent(false);
5498 mWindow->consumeFocusEvent(false);
5499 mSecondWindow->consumeFocusEvent(true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005500 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005501
5502 // Ensure that additional state changes from InputReader are not sent to the window.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005503 notifyPointerCaptureChanged({});
5504 notifyPointerCaptureChanged(request);
5505 notifyPointerCaptureChanged({});
Prabir Pradhan99987712020-11-10 18:43:05 -08005506 mWindow->assertNoEvents();
5507 mSecondWindow->assertNoEvents();
5508 mFakePolicy->assertSetPointerCaptureNotCalled();
5509}
5510
5511TEST_F(InputDispatcherPointerCaptureTests, UnexpectedStateChangeDisablesPointerCapture) {
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005512 auto request = requestAndVerifyPointerCapture(mWindow, true);
Prabir Pradhan99987712020-11-10 18:43:05 -08005513
5514 // InputReader unexpectedly disables and enables pointer capture.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005515 notifyPointerCaptureChanged({});
5516 notifyPointerCaptureChanged(request);
Prabir Pradhan99987712020-11-10 18:43:05 -08005517
5518 // Ensure that Pointer Capture is disabled.
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005519 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan99987712020-11-10 18:43:05 -08005520 mWindow->consumeCaptureEvent(false);
5521 mWindow->assertNoEvents();
5522}
5523
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005524TEST_F(InputDispatcherPointerCaptureTests, OutOfOrderRequests) {
5525 requestAndVerifyPointerCapture(mWindow, true);
5526
5527 // The first window loses focus.
5528 setFocusedWindow(mSecondWindow);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005529 mFakePolicy->assertSetPointerCaptureCalled(false);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005530 mWindow->consumeCaptureEvent(false);
5531
5532 // Request Pointer Capture from the second window before the notification from InputReader
5533 // arrives.
5534 mDispatcher->requestPointerCapture(mSecondWindow->getToken(), true);
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005535 auto request = mFakePolicy->assertSetPointerCaptureCalled(true);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005536
5537 // InputReader notifies Pointer Capture was disabled (because of the focus change).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005538 notifyPointerCaptureChanged({});
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005539
5540 // InputReader notifies Pointer Capture was enabled (because of mSecondWindow's request).
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005541 notifyPointerCaptureChanged(request);
Prabir Pradhan167e6d92021-02-04 16:18:17 -08005542
5543 mSecondWindow->consumeFocusEvent(true);
5544 mSecondWindow->consumeCaptureEvent(true);
5545}
5546
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00005547TEST_F(InputDispatcherPointerCaptureTests, EnableRequestFollowsSequenceNumbers) {
5548 // App repeatedly enables and disables capture.
5549 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5550 auto firstRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5551 mDispatcher->requestPointerCapture(mWindow->getToken(), false);
5552 mFakePolicy->assertSetPointerCaptureCalled(false);
5553 mDispatcher->requestPointerCapture(mWindow->getToken(), true);
5554 auto secondRequest = mFakePolicy->assertSetPointerCaptureCalled(true);
5555
5556 // InputReader notifies that PointerCapture has been enabled for the first request. Since the
5557 // first request is now stale, this should do nothing.
5558 notifyPointerCaptureChanged(firstRequest);
5559 mWindow->assertNoEvents();
5560
5561 // InputReader notifies that the second request was enabled.
5562 notifyPointerCaptureChanged(secondRequest);
5563 mWindow->consumeCaptureEvent(true);
5564}
5565
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005566class InputDispatcherUntrustedTouchesTest : public InputDispatcherTest {
5567protected:
5568 constexpr static const float MAXIMUM_OBSCURING_OPACITY = 0.8;
Bernardo Rufino7393d172021-02-26 13:56:11 +00005569
5570 constexpr static const float OPACITY_ABOVE_THRESHOLD = 0.9;
5571 static_assert(OPACITY_ABOVE_THRESHOLD > MAXIMUM_OBSCURING_OPACITY);
5572
5573 constexpr static const float OPACITY_BELOW_THRESHOLD = 0.7;
5574 static_assert(OPACITY_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5575
5576 // When combined twice, ie 1 - (1 - 0.5)*(1 - 0.5) = 0.75 < 8, is still below the threshold
5577 constexpr static const float OPACITY_FAR_BELOW_THRESHOLD = 0.5;
5578 static_assert(OPACITY_FAR_BELOW_THRESHOLD < MAXIMUM_OBSCURING_OPACITY);
5579 static_assert(1 - (1 - OPACITY_FAR_BELOW_THRESHOLD) * (1 - OPACITY_FAR_BELOW_THRESHOLD) <
5580 MAXIMUM_OBSCURING_OPACITY);
5581
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005582 static const int32_t TOUCHED_APP_UID = 10001;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005583 static const int32_t APP_B_UID = 10002;
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005584 static const int32_t APP_C_UID = 10003;
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005585
5586 sp<FakeWindowHandle> mTouchWindow;
5587
5588 virtual void SetUp() override {
5589 InputDispatcherTest::SetUp();
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005590 mTouchWindow = getWindow(TOUCHED_APP_UID, "Touched");
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005591 mDispatcher->setBlockUntrustedTouchesMode(android::os::BlockUntrustedTouchesMode::BLOCK);
5592 mDispatcher->setMaximumObscuringOpacityForTouch(MAXIMUM_OBSCURING_OPACITY);
5593 }
5594
5595 virtual void TearDown() override {
5596 InputDispatcherTest::TearDown();
5597 mTouchWindow.clear();
5598 }
5599
chaviw3277faf2021-05-19 16:45:23 -05005600 sp<FakeWindowHandle> getOccludingWindow(int32_t uid, std::string name, TouchOcclusionMode mode,
5601 float alpha = 1.0f) {
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005602 sp<FakeWindowHandle> window = getWindow(uid, name);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005603 window->setTouchable(false);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005604 window->setTouchOcclusionMode(mode);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005605 window->setAlpha(alpha);
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005606 return window;
5607 }
5608
5609 sp<FakeWindowHandle> getWindow(int32_t uid, std::string name) {
5610 std::shared_ptr<FakeApplicationHandle> app = std::make_shared<FakeApplicationHandle>();
5611 sp<FakeWindowHandle> window =
5612 new FakeWindowHandle(app, mDispatcher, name, ADISPLAY_ID_DEFAULT);
5613 // Generate an arbitrary PID based on the UID
5614 window->setOwnerInfo(1777 + (uid % 10000), uid);
5615 return window;
5616 }
5617
5618 void touch(const std::vector<PointF>& points = {PointF{100, 200}}) {
5619 NotifyMotionArgs args =
5620 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
5621 ADISPLAY_ID_DEFAULT, points);
5622 mDispatcher->notifyMotion(&args);
5623 }
5624};
5625
5626TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithBlockUntrustedOcclusionMode_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005627 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005628 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005629 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005630
5631 touch();
5632
5633 mTouchWindow->assertNoEvents();
5634}
5635
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005636TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufino7393d172021-02-26 13:56:11 +00005637 WindowWithBlockUntrustedOcclusionModeWithOpacityBelowThreshold_BlocksTouch) {
5638 const sp<FakeWindowHandle>& w =
5639 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.7f);
5640 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5641
5642 touch();
5643
5644 mTouchWindow->assertNoEvents();
5645}
5646
5647TEST_F(InputDispatcherUntrustedTouchesTest,
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005648 WindowWithBlockUntrustedOcclusionMode_DoesNotReceiveTouch) {
5649 const sp<FakeWindowHandle>& w =
5650 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5651 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5652
5653 touch();
5654
5655 w->assertNoEvents();
5656}
5657
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005658TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithAllowOcclusionMode_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005659 const sp<FakeWindowHandle>& w = getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::ALLOW);
5660 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005661
5662 touch();
5663
5664 mTouchWindow->consumeAnyMotionDown();
5665}
5666
5667TEST_F(InputDispatcherUntrustedTouchesTest, TouchOutsideOccludingWindow_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005668 const sp<FakeWindowHandle>& w =
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005669 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005670 w->setFrame(Rect(0, 0, 50, 50));
5671 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005672
5673 touch({PointF{100, 100}});
5674
5675 mTouchWindow->consumeAnyMotionDown();
5676}
5677
5678TEST_F(InputDispatcherUntrustedTouchesTest, WindowFromSameUid_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005679 const sp<FakeWindowHandle>& w =
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005680 getOccludingWindow(TOUCHED_APP_UID, "A", TouchOcclusionMode::BLOCK_UNTRUSTED);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005681 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5682
5683 touch();
5684
5685 mTouchWindow->consumeAnyMotionDown();
5686}
5687
5688TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_AllowsTouch) {
5689 const sp<FakeWindowHandle>& w =
5690 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5691 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005692
5693 touch();
5694
5695 mTouchWindow->consumeAnyMotionDown();
5696}
5697
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005698TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithZeroOpacity_DoesNotReceiveTouch) {
5699 const sp<FakeWindowHandle>& w =
5700 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
5701 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5702
5703 touch();
5704
5705 w->assertNoEvents();
5706}
5707
5708/**
5709 * This is important to make sure apps can't indirectly learn the position of touches (outside vs
5710 * inside) while letting them pass-through. Note that even though touch passes through the occluding
5711 * window, the occluding window will still receive ACTION_OUTSIDE event.
5712 */
5713TEST_F(InputDispatcherUntrustedTouchesTest,
5714 WindowWithZeroOpacityAndWatchOutside_ReceivesOutsideEvent) {
5715 const sp<FakeWindowHandle>& w =
5716 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005717 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005718 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5719
5720 touch();
5721
5722 w->consumeMotionOutside();
5723}
5724
5725TEST_F(InputDispatcherUntrustedTouchesTest, OutsideEvent_HasZeroCoordinates) {
5726 const sp<FakeWindowHandle>& w =
5727 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED, 0.0f);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08005728 w->setWatchOutsideTouch(true);
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005729 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5730
5731 touch();
5732
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08005733 w->consumeMotionOutsideWithZeroedCoords();
Bernardo Rufinoa43a5a42021-02-17 12:21:14 +00005734}
5735
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005736TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityBelowThreshold_AllowsTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005737 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005738 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5739 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005740 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5741
5742 touch();
5743
5744 mTouchWindow->consumeAnyMotionDown();
5745}
5746
5747TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAtThreshold_AllowsTouch) {
5748 const sp<FakeWindowHandle>& w =
5749 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5750 MAXIMUM_OBSCURING_OPACITY);
5751 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005752
5753 touch();
5754
5755 mTouchWindow->consumeAnyMotionDown();
5756}
5757
5758TEST_F(InputDispatcherUntrustedTouchesTest, WindowWithOpacityAboveThreshold_BlocksTouch) {
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005759 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005760 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5761 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005762 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5763
5764 touch();
5765
5766 mTouchWindow->assertNoEvents();
5767}
5768
5769TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityAboveThreshold_BlocksTouch) {
5770 // Resulting opacity = 1 - (1 - 0.7)*(1 - 0.7) = .91
5771 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005772 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5773 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005774 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005775 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5776 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005777 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5778
5779 touch();
5780
5781 mTouchWindow->assertNoEvents();
5782}
5783
5784TEST_F(InputDispatcherUntrustedTouchesTest, WindowsWithCombinedOpacityBelowThreshold_AllowsTouch) {
5785 // Resulting opacity = 1 - (1 - 0.5)*(1 - 0.5) = .75
5786 const sp<FakeWindowHandle>& w1 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005787 getOccludingWindow(APP_B_UID, "B1", TouchOcclusionMode::USE_OPACITY,
5788 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005789 const sp<FakeWindowHandle>& w2 =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005790 getOccludingWindow(APP_B_UID, "B2", TouchOcclusionMode::USE_OPACITY,
5791 OPACITY_FAR_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005792 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5793
5794 touch();
5795
5796 mTouchWindow->consumeAnyMotionDown();
5797}
5798
5799TEST_F(InputDispatcherUntrustedTouchesTest,
5800 WindowsFromDifferentAppsEachBelowThreshold_AllowsTouch) {
5801 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005802 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5803 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005804 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005805 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5806 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005807 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5808
5809 touch();
5810
5811 mTouchWindow->consumeAnyMotionDown();
5812}
5813
5814TEST_F(InputDispatcherUntrustedTouchesTest, WindowsFromDifferentAppsOneAboveThreshold_BlocksTouch) {
5815 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005816 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5817 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005818 const sp<FakeWindowHandle>& wC =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005819 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5820 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino1d0d1f22021-02-12 15:08:43 +00005821 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
Bernardo Rufinoc3b7b8c2021-01-29 17:38:07 +00005822
5823 touch();
5824
5825 mTouchWindow->assertNoEvents();
5826}
5827
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005828TEST_F(InputDispatcherUntrustedTouchesTest,
5829 WindowWithOpacityAboveThresholdAndSelfWindow_BlocksTouch) {
5830 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005831 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5832 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005833 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005834 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5835 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005836 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5837
5838 touch();
5839
5840 mTouchWindow->assertNoEvents();
5841}
5842
5843TEST_F(InputDispatcherUntrustedTouchesTest,
5844 WindowWithOpacityBelowThresholdAndSelfWindow_AllowsTouch) {
5845 const sp<FakeWindowHandle>& wA =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005846 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5847 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005848 const sp<FakeWindowHandle>& wB =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005849 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5850 OPACITY_BELOW_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005851 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wA, wB, mTouchWindow}}});
5852
5853 touch();
5854
5855 mTouchWindow->consumeAnyMotionDown();
5856}
5857
5858TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithOpacityAboveThreshold_AllowsTouch) {
5859 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005860 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::USE_OPACITY,
5861 OPACITY_ABOVE_THRESHOLD);
Bernardo Rufino6d52e542021-02-15 18:38:10 +00005862 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5863
5864 touch();
5865
5866 mTouchWindow->consumeAnyMotionDown();
5867}
5868
5869TEST_F(InputDispatcherUntrustedTouchesTest, SelfWindowWithBlockUntrustedMode_AllowsTouch) {
5870 const sp<FakeWindowHandle>& w =
5871 getOccludingWindow(TOUCHED_APP_UID, "T", TouchOcclusionMode::BLOCK_UNTRUSTED);
5872 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5873
5874 touch();
5875
5876 mTouchWindow->consumeAnyMotionDown();
5877}
5878
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005879TEST_F(InputDispatcherUntrustedTouchesTest,
5880 OpacityThresholdIs0AndWindowAboveThreshold_BlocksTouch) {
5881 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5882 const sp<FakeWindowHandle>& w =
5883 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.1f);
5884 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5885
5886 touch();
5887
5888 mTouchWindow->assertNoEvents();
5889}
5890
5891TEST_F(InputDispatcherUntrustedTouchesTest, OpacityThresholdIs0AndWindowAtThreshold_AllowsTouch) {
5892 mDispatcher->setMaximumObscuringOpacityForTouch(0.0f);
5893 const sp<FakeWindowHandle>& w =
5894 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY, 0.0f);
5895 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5896
5897 touch();
5898
5899 mTouchWindow->consumeAnyMotionDown();
5900}
5901
5902TEST_F(InputDispatcherUntrustedTouchesTest,
5903 OpacityThresholdIs1AndWindowBelowThreshold_AllowsTouch) {
5904 mDispatcher->setMaximumObscuringOpacityForTouch(1.0f);
5905 const sp<FakeWindowHandle>& w =
Bernardo Rufino7393d172021-02-26 13:56:11 +00005906 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5907 OPACITY_ABOVE_THRESHOLD);
5908 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5909
5910 touch();
5911
5912 mTouchWindow->consumeAnyMotionDown();
5913}
5914
5915TEST_F(InputDispatcherUntrustedTouchesTest,
5916 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromSameApp_BlocksTouch) {
5917 const sp<FakeWindowHandle>& w1 =
5918 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5919 OPACITY_BELOW_THRESHOLD);
5920 const sp<FakeWindowHandle>& w2 =
5921 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::USE_OPACITY,
5922 OPACITY_BELOW_THRESHOLD);
5923 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w1, w2, mTouchWindow}}});
5924
5925 touch();
5926
5927 mTouchWindow->assertNoEvents();
5928}
5929
5930/**
5931 * Window B of BLOCK_UNTRUSTED occlusion mode is enough to block the touch, we're testing that the
5932 * addition of another window (C) of USE_OPACITY occlusion mode and opacity below the threshold
5933 * (which alone would result in allowing touches) does not affect the blocking behavior.
5934 */
5935TEST_F(InputDispatcherUntrustedTouchesTest,
5936 WindowWithBlockUntrustedModeAndWindowWithOpacityBelowFromDifferentApps_BlocksTouch) {
5937 const sp<FakeWindowHandle>& wB =
5938 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED,
5939 OPACITY_BELOW_THRESHOLD);
5940 const sp<FakeWindowHandle>& wC =
5941 getOccludingWindow(APP_C_UID, "C", TouchOcclusionMode::USE_OPACITY,
5942 OPACITY_BELOW_THRESHOLD);
5943 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {wB, wC, mTouchWindow}}});
5944
5945 touch();
5946
5947 mTouchWindow->assertNoEvents();
5948}
5949
5950/**
5951 * This test is testing that a window from a different UID but with same application token doesn't
5952 * block the touch. Apps can share the application token for close UI collaboration for example.
5953 */
5954TEST_F(InputDispatcherUntrustedTouchesTest,
5955 WindowWithSameApplicationTokenFromDifferentApp_AllowsTouch) {
5956 const sp<FakeWindowHandle>& w =
5957 getOccludingWindow(APP_B_UID, "B", TouchOcclusionMode::BLOCK_UNTRUSTED);
5958 w->setApplicationToken(mTouchWindow->getApplicationToken());
Bernardo Rufinoccd3dd62021-02-15 18:47:42 +00005959 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {w, mTouchWindow}}});
5960
5961 touch();
5962
5963 mTouchWindow->consumeAnyMotionDown();
5964}
5965
arthurhungb89ccb02020-12-30 16:19:01 +08005966class InputDispatcherDragTests : public InputDispatcherTest {
5967protected:
5968 std::shared_ptr<FakeApplicationHandle> mApp;
5969 sp<FakeWindowHandle> mWindow;
5970 sp<FakeWindowHandle> mSecondWindow;
5971 sp<FakeWindowHandle> mDragWindow;
5972
5973 void SetUp() override {
5974 InputDispatcherTest::SetUp();
5975 mApp = std::make_shared<FakeApplicationHandle>();
5976 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
5977 mWindow->setFrame(Rect(0, 0, 100, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005978
5979 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
5980 mSecondWindow->setFrame(Rect(100, 0, 200, 100));
arthurhungb89ccb02020-12-30 16:19:01 +08005981
5982 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
5983 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
5984 }
5985
5986 // Start performing drag, we will create a drag window and transfer touch to it.
5987 void performDrag() {
5988 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
5989 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
5990 {50, 50}))
5991 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
5992
5993 // Window should receive motion event.
5994 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
5995
5996 // The drag window covers the entire display
5997 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
5998 mDispatcher->setInputWindows(
5999 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6000
6001 // Transfer touch focus to the drag window
6002 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6003 true /* isDragDrop */);
6004 mWindow->consumeMotionCancel();
6005 mDragWindow->consumeMotionDown();
6006 }
arthurhung6d4bed92021-03-17 11:59:33 +08006007
6008 // Start performing drag, we will create a drag window and transfer touch to it.
6009 void performStylusDrag() {
6010 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6011 injectMotionEvent(mDispatcher,
6012 MotionEventBuilder(AMOTION_EVENT_ACTION_DOWN,
6013 AINPUT_SOURCE_STYLUS)
6014 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6015 .pointer(PointerBuilder(0,
6016 AMOTION_EVENT_TOOL_TYPE_STYLUS)
6017 .x(50)
6018 .y(50))
6019 .build()));
6020 mWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6021
6022 // The drag window covers the entire display
6023 mDragWindow = new FakeWindowHandle(mApp, mDispatcher, "DragWindow", ADISPLAY_ID_DEFAULT);
6024 mDispatcher->setInputWindows(
6025 {{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6026
6027 // Transfer touch focus to the drag window
6028 mDispatcher->transferTouchFocus(mWindow->getToken(), mDragWindow->getToken(),
6029 true /* isDragDrop */);
6030 mWindow->consumeMotionCancel();
6031 mDragWindow->consumeMotionDown();
6032 }
arthurhungb89ccb02020-12-30 16:19:01 +08006033};
6034
6035TEST_F(InputDispatcherDragTests, DragEnterAndDragExit) {
6036 performDrag();
6037
6038 // Move on window.
6039 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6040 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6041 ADISPLAY_ID_DEFAULT, {50, 50}))
6042 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6043 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6044 mWindow->consumeDragEvent(false, 50, 50);
6045 mSecondWindow->assertNoEvents();
6046
6047 // Move to another window.
6048 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6049 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6050 ADISPLAY_ID_DEFAULT, {150, 50}))
6051 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6052 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6053 mWindow->consumeDragEvent(true, 150, 50);
6054 mSecondWindow->consumeDragEvent(false, 50, 50);
6055
6056 // Move back to original window.
6057 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6058 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6059 ADISPLAY_ID_DEFAULT, {50, 50}))
6060 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6061 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6062 mWindow->consumeDragEvent(false, 50, 50);
6063 mSecondWindow->consumeDragEvent(true, -50, 50);
6064
6065 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6066 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
6067 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6068 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6069 mWindow->assertNoEvents();
6070 mSecondWindow->assertNoEvents();
6071}
6072
arthurhungf452d0b2021-01-06 00:19:52 +08006073TEST_F(InputDispatcherDragTests, DragAndDrop) {
6074 performDrag();
6075
6076 // Move on window.
6077 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6078 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6079 ADISPLAY_ID_DEFAULT, {50, 50}))
6080 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6081 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6082 mWindow->consumeDragEvent(false, 50, 50);
6083 mSecondWindow->assertNoEvents();
6084
6085 // Move to another window.
6086 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6087 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6088 ADISPLAY_ID_DEFAULT, {150, 50}))
6089 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6090 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6091 mWindow->consumeDragEvent(true, 150, 50);
6092 mSecondWindow->consumeDragEvent(false, 50, 50);
6093
6094 // drop to another window.
6095 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6096 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6097 {150, 50}))
6098 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6099 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6100 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6101 mWindow->assertNoEvents();
6102 mSecondWindow->assertNoEvents();
6103}
6104
arthurhung6d4bed92021-03-17 11:59:33 +08006105TEST_F(InputDispatcherDragTests, StylusDragAndDrop) {
6106 performStylusDrag();
6107
6108 // Move on window and keep button pressed.
6109 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6110 injectMotionEvent(mDispatcher,
6111 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6112 .buttonState(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY)
6113 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6114 .x(50)
6115 .y(50))
6116 .build()))
6117 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6118 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6119 mWindow->consumeDragEvent(false, 50, 50);
6120 mSecondWindow->assertNoEvents();
6121
6122 // Move to another window and release button, expect to drop item.
6123 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6124 injectMotionEvent(mDispatcher,
6125 MotionEventBuilder(AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_STYLUS)
6126 .buttonState(0)
6127 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6128 .x(150)
6129 .y(50))
6130 .build()))
6131 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6132 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6133 mWindow->assertNoEvents();
6134 mSecondWindow->assertNoEvents();
6135 mFakePolicy->assertDropTargetEquals(mSecondWindow->getToken());
6136
6137 // nothing to the window.
6138 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6139 injectMotionEvent(mDispatcher,
6140 MotionEventBuilder(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_STYLUS)
6141 .buttonState(0)
6142 .pointer(PointerBuilder(0, AMOTION_EVENT_TOOL_TYPE_STYLUS)
6143 .x(150)
6144 .y(50))
6145 .build()))
6146 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6147 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6148 mWindow->assertNoEvents();
6149 mSecondWindow->assertNoEvents();
6150}
6151
Arthur Hung6d0571e2021-04-09 20:18:16 +08006152TEST_F(InputDispatcherDragTests, DragAndDrop_InvalidWindow) {
6153 performDrag();
6154
6155 // Set second window invisible.
6156 mSecondWindow->setVisible(false);
6157 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mDragWindow, mWindow, mSecondWindow}}});
6158
6159 // Move on window.
6160 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6161 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6162 ADISPLAY_ID_DEFAULT, {50, 50}))
6163 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6164 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6165 mWindow->consumeDragEvent(false, 50, 50);
6166 mSecondWindow->assertNoEvents();
6167
6168 // Move to another window.
6169 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6170 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6171 ADISPLAY_ID_DEFAULT, {150, 50}))
6172 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6173 mDragWindow->consumeMotionMove(ADISPLAY_ID_DEFAULT);
6174 mWindow->consumeDragEvent(true, 150, 50);
6175 mSecondWindow->assertNoEvents();
6176
6177 // drop to another window.
6178 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6179 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6180 {150, 50}))
6181 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6182 mDragWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6183 mFakePolicy->assertDropTargetEquals(nullptr);
6184 mWindow->assertNoEvents();
6185 mSecondWindow->assertNoEvents();
6186}
6187
Vishnu Nair062a8672021-09-03 16:07:44 -07006188class InputDispatcherDropInputFeatureTest : public InputDispatcherTest {};
6189
6190TEST_F(InputDispatcherDropInputFeatureTest, WindowDropsInput) {
6191 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6192 sp<FakeWindowHandle> window =
6193 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006194 window->setDropInput(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006195 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6196 window->setFocusable(true);
6197 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6198 setFocusedWindow(window);
6199 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6200
6201 // With the flag set, window should not get any input
6202 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6203 mDispatcher->notifyKey(&keyArgs);
6204 window->assertNoEvents();
6205
6206 NotifyMotionArgs motionArgs =
6207 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6208 ADISPLAY_ID_DEFAULT);
6209 mDispatcher->notifyMotion(&motionArgs);
6210 window->assertNoEvents();
6211
6212 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006213 window->setDropInput(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006214 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
6215
6216 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6217 mDispatcher->notifyKey(&keyArgs);
6218 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6219
6220 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6221 ADISPLAY_ID_DEFAULT);
6222 mDispatcher->notifyMotion(&motionArgs);
6223 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6224 window->assertNoEvents();
6225}
6226
6227TEST_F(InputDispatcherDropInputFeatureTest, ObscuredWindowDropsInput) {
6228 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6229 std::make_shared<FakeApplicationHandle>();
6230 sp<FakeWindowHandle> obscuringWindow =
6231 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6232 ADISPLAY_ID_DEFAULT);
6233 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6234 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006235 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006236 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6237 sp<FakeWindowHandle> window =
6238 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006239 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006240 window->setOwnerInfo(222, 222);
6241 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6242 window->setFocusable(true);
6243 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6244 setFocusedWindow(window);
6245 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6246
6247 // With the flag set, window should not get any input
6248 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6249 mDispatcher->notifyKey(&keyArgs);
6250 window->assertNoEvents();
6251
6252 NotifyMotionArgs motionArgs =
6253 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6254 ADISPLAY_ID_DEFAULT);
6255 mDispatcher->notifyMotion(&motionArgs);
6256 window->assertNoEvents();
6257
6258 // With the flag cleared, the window should get input
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006259 window->setDropInputIfObscured(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006260 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6261
6262 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6263 mDispatcher->notifyKey(&keyArgs);
6264 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6265
6266 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6267 ADISPLAY_ID_DEFAULT);
6268 mDispatcher->notifyMotion(&motionArgs);
6269 window->consumeMotionDown(ADISPLAY_ID_DEFAULT, AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED);
6270 window->assertNoEvents();
6271}
6272
6273TEST_F(InputDispatcherDropInputFeatureTest, UnobscuredWindowGetsInput) {
6274 std::shared_ptr<FakeApplicationHandle> obscuringApplication =
6275 std::make_shared<FakeApplicationHandle>();
6276 sp<FakeWindowHandle> obscuringWindow =
6277 new FakeWindowHandle(obscuringApplication, mDispatcher, "obscuringWindow",
6278 ADISPLAY_ID_DEFAULT);
6279 obscuringWindow->setFrame(Rect(0, 0, 50, 50));
6280 obscuringWindow->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006281 obscuringWindow->setTouchable(false);
Vishnu Nair062a8672021-09-03 16:07:44 -07006282 std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
6283 sp<FakeWindowHandle> window =
6284 new FakeWindowHandle(application, mDispatcher, "Test window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006285 window->setDropInputIfObscured(true);
Vishnu Nair062a8672021-09-03 16:07:44 -07006286 window->setOwnerInfo(222, 222);
6287 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6288 window->setFocusable(true);
6289 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {obscuringWindow, window}}});
6290 setFocusedWindow(window);
6291 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6292
6293 // With the flag set, window should not get any input
6294 NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
6295 mDispatcher->notifyKey(&keyArgs);
6296 window->assertNoEvents();
6297
6298 NotifyMotionArgs motionArgs =
6299 generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6300 ADISPLAY_ID_DEFAULT);
6301 mDispatcher->notifyMotion(&motionArgs);
6302 window->assertNoEvents();
6303
6304 // When the window is no longer obscured because it went on top, it should get input
6305 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, obscuringWindow}}});
6306
6307 keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_UP, ADISPLAY_ID_DEFAULT);
6308 mDispatcher->notifyKey(&keyArgs);
6309 window->consumeKeyUp(ADISPLAY_ID_DEFAULT);
6310
6311 motionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
6312 ADISPLAY_ID_DEFAULT);
6313 mDispatcher->notifyMotion(&motionArgs);
6314 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6315 window->assertNoEvents();
6316}
6317
Antonio Kantekf16f2832021-09-28 04:39:20 +00006318class InputDispatcherTouchModeChangedTests : public InputDispatcherTest {
6319protected:
6320 std::shared_ptr<FakeApplicationHandle> mApp;
6321 sp<FakeWindowHandle> mWindow;
6322 sp<FakeWindowHandle> mSecondWindow;
6323
6324 void SetUp() override {
6325 InputDispatcherTest::SetUp();
6326
6327 mApp = std::make_shared<FakeApplicationHandle>();
6328 mWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow", ADISPLAY_ID_DEFAULT);
6329 mWindow->setFocusable(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006330 setFocusedWindow(mWindow);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006331 mSecondWindow = new FakeWindowHandle(mApp, mDispatcher, "TestWindow2", ADISPLAY_ID_DEFAULT);
6332 mSecondWindow->setFocusable(true);
6333
6334 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, mApp);
6335 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow, mSecondWindow}}});
Antonio Kantekf16f2832021-09-28 04:39:20 +00006336 mWindow->consumeFocusEvent(true);
Antonio Kantek26defcf2022-02-08 01:12:27 +00006337
6338 // Set initial touch mode to InputDispatcher::kDefaultInTouchMode.
Prabir Pradhan4df80f52022-04-05 18:33:16 +00006339 if (mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, INJECTOR_PID,
6340 INJECTOR_UID, /* hasPermission */ true)) {
Antonio Kantek48710e42022-03-24 14:19:30 -07006341 mWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6342 mSecondWindow->consumeTouchModeEvent(InputDispatcher::kDefaultInTouchMode);
6343 }
Antonio Kantekf16f2832021-09-28 04:39:20 +00006344 }
6345
Antonio Kantekea47acb2021-12-23 12:41:25 -08006346 void changeAndVerifyTouchMode(bool inTouchMode, int32_t pid, int32_t uid, bool hasPermission) {
Antonio Kantek26defcf2022-02-08 01:12:27 +00006347 ASSERT_TRUE(mDispatcher->setInTouchMode(inTouchMode, pid, uid, hasPermission));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006348 mWindow->consumeTouchModeEvent(inTouchMode);
6349 mSecondWindow->consumeTouchModeEvent(inTouchMode);
6350 }
6351};
6352
Antonio Kantek26defcf2022-02-08 01:12:27 +00006353TEST_F(InputDispatcherTouchModeChangedTests, FocusedWindowCanChangeTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006354 const WindowInfo& windowInfo = *mWindow->getInfo();
6355 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, windowInfo.ownerPid,
6356 windowInfo.ownerUid, /* hasPermission */ false);
Antonio Kantekf16f2832021-09-28 04:39:20 +00006357}
6358
Antonio Kantek26defcf2022-02-08 01:12:27 +00006359TEST_F(InputDispatcherTouchModeChangedTests, NonFocusedWindowOwnerCannotChangeTouchMode) {
6360 const WindowInfo& windowInfo = *mWindow->getInfo();
6361 int32_t ownerPid = windowInfo.ownerPid;
6362 int32_t ownerUid = windowInfo.ownerUid;
6363 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6364 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode, ownerPid,
6365 ownerUid, /* hasPermission */ false));
6366 mWindow->assertNoEvents();
6367 mSecondWindow->assertNoEvents();
6368}
6369
6370TEST_F(InputDispatcherTouchModeChangedTests, NonWindowOwnerMayChangeTouchModeOnPermissionGranted) {
6371 const WindowInfo& windowInfo = *mWindow->getInfo();
6372 int32_t ownerPid = windowInfo.ownerPid;
6373 int32_t ownerUid = windowInfo.ownerUid;
6374 mWindow->setOwnerInfo(/* pid */ -1, /* uid */ -1);
6375 changeAndVerifyTouchMode(!InputDispatcher::kDefaultInTouchMode, ownerPid, ownerUid,
6376 /* hasPermission */ true);
6377}
6378
Antonio Kantekf16f2832021-09-28 04:39:20 +00006379TEST_F(InputDispatcherTouchModeChangedTests, EventIsNotGeneratedIfNotChangingTouchMode) {
Antonio Kantekea47acb2021-12-23 12:41:25 -08006380 const WindowInfo& windowInfo = *mWindow->getInfo();
Antonio Kantek26defcf2022-02-08 01:12:27 +00006381 ASSERT_FALSE(mDispatcher->setInTouchMode(InputDispatcher::kDefaultInTouchMode,
6382 windowInfo.ownerPid, windowInfo.ownerUid,
6383 /* hasPermission */ true));
Antonio Kantekf16f2832021-09-28 04:39:20 +00006384 mWindow->assertNoEvents();
6385 mSecondWindow->assertNoEvents();
6386}
6387
Antonio Kantek48710e42022-03-24 14:19:30 -07006388TEST_F(InputDispatcherTouchModeChangedTests, CanChangeTouchModeWhenOwningLastInteractedWindow) {
6389 // Interact with the window first.
6390 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher, ADISPLAY_ID_DEFAULT))
6391 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6392 mWindow->consumeKeyDown(ADISPLAY_ID_DEFAULT);
6393
6394 // Then remove focus.
6395 mWindow->setFocusable(false);
6396 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
6397
6398 // Assert that caller can switch touch mode by owning one of the last interacted window.
6399 const WindowInfo& windowInfo = *mWindow->getInfo();
6400 ASSERT_TRUE(mDispatcher->setInTouchMode(!InputDispatcher::kDefaultInTouchMode,
6401 windowInfo.ownerPid, windowInfo.ownerUid,
6402 /* hasPermission= */ false));
6403}
6404
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006405class InputDispatcherSpyWindowTest : public InputDispatcherTest {
6406public:
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006407 sp<FakeWindowHandle> createSpy() {
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006408 std::shared_ptr<FakeApplicationHandle> application =
6409 std::make_shared<FakeApplicationHandle>();
6410 std::string name = "Fake Spy ";
6411 name += std::to_string(mSpyCount++);
6412 sp<FakeWindowHandle> spy =
6413 new FakeWindowHandle(application, mDispatcher, name.c_str(), ADISPLAY_ID_DEFAULT);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006414 spy->setSpy(true);
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006415 spy->setTrustedOverlay(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006416 return spy;
6417 }
6418
6419 sp<FakeWindowHandle> createForeground() {
6420 std::shared_ptr<FakeApplicationHandle> application =
6421 std::make_shared<FakeApplicationHandle>();
6422 sp<FakeWindowHandle> window =
6423 new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006424 window->setFocusable(true);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006425 return window;
6426 }
6427
6428private:
6429 int mSpyCount{0};
6430};
6431
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006432using InputDispatcherSpyWindowDeathTest = InputDispatcherSpyWindowTest;
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006433/**
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006434 * Adding a spy window that is not a trusted overlay causes Dispatcher to abort.
6435 */
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006436TEST_F(InputDispatcherSpyWindowDeathTest, UntrustedSpy_AbortsDispatcher) {
6437 ScopedSilentDeath _silentDeath;
6438
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006439 auto spy = createSpy();
Prabir Pradhan5c85e052021-12-22 02:27:12 -08006440 spy->setTrustedOverlay(false);
6441 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}}),
6442 ".* not a trusted overlay");
6443}
6444
6445/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006446 * Input injection into a display with a spy window but no foreground windows should succeed.
6447 */
6448TEST_F(InputDispatcherSpyWindowTest, NoForegroundWindow) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006449 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006450 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy}}});
6451
6452 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6453 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6454 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6455 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6456}
6457
6458/**
6459 * Verify the order in which different input windows receive events. The touched foreground window
6460 * (if there is one) should always receive the event first. When there are multiple spy windows, the
6461 * spy windows will receive the event according to their Z-order, where the top-most spy window will
6462 * receive events before ones belows it.
6463 *
6464 * Here, we set up a scenario with four windows in the following Z order from the top:
6465 * spy1, spy2, window, spy3.
6466 * We then inject an event and verify that the foreground "window" receives it first, followed by
6467 * "spy1" and "spy2". The "spy3" does not receive the event because it is underneath the foreground
6468 * window.
6469 */
6470TEST_F(InputDispatcherSpyWindowTest, ReceivesInputInOrder) {
6471 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006472 auto spy1 = createSpy();
6473 auto spy2 = createSpy();
6474 auto spy3 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006475 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window, spy3}}});
6476 const std::vector<sp<FakeWindowHandle>> channels{spy1, spy2, window, spy3};
6477 const size_t numChannels = channels.size();
6478
Michael Wright8e9a8562022-02-09 13:44:29 +00006479 base::unique_fd epollFd(epoll_create1(EPOLL_CLOEXEC));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006480 if (!epollFd.ok()) {
6481 FAIL() << "Failed to create epoll fd";
6482 }
6483
6484 for (size_t i = 0; i < numChannels; i++) {
6485 struct epoll_event event = {.events = EPOLLIN, .data.u64 = i};
6486 if (epoll_ctl(epollFd.get(), EPOLL_CTL_ADD, channels[i]->getChannelFd(), &event) < 0) {
6487 FAIL() << "Failed to add fd to epoll";
6488 }
6489 }
6490
6491 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6492 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6493 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6494
6495 std::vector<size_t> eventOrder;
6496 std::vector<struct epoll_event> events(numChannels);
6497 for (;;) {
6498 const int nFds = epoll_wait(epollFd.get(), events.data(), static_cast<int>(numChannels),
6499 (100ms).count());
6500 if (nFds < 0) {
6501 FAIL() << "Failed to call epoll_wait";
6502 }
6503 if (nFds == 0) {
6504 break; // epoll_wait timed out
6505 }
6506 for (int i = 0; i < nFds; i++) {
6507 ASSERT_EQ(EPOLLIN, events[i].events);
6508 eventOrder.push_back(events[i].data.u64);
6509 channels[i]->consumeMotionDown();
6510 }
6511 }
6512
6513 // Verify the order in which the events were received.
6514 EXPECT_EQ(3u, eventOrder.size());
6515 EXPECT_EQ(2u, eventOrder[0]); // index 2: window
6516 EXPECT_EQ(0u, eventOrder[1]); // index 0: spy1
6517 EXPECT_EQ(1u, eventOrder[2]); // index 1: spy2
6518}
6519
6520/**
6521 * A spy window using the NOT_TOUCHABLE flag does not receive events.
6522 */
6523TEST_F(InputDispatcherSpyWindowTest, NotTouchable) {
6524 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006525 auto spy = createSpy();
6526 spy->setTouchable(false);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006527 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6528
6529 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6530 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6531 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6532 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6533 spy->assertNoEvents();
6534}
6535
6536/**
6537 * A spy window will only receive gestures that originate within its touchable region. Gestures that
6538 * have their ACTION_DOWN outside of the touchable region of the spy window will not be dispatched
6539 * to the window.
6540 */
6541TEST_F(InputDispatcherSpyWindowTest, TouchableRegion) {
6542 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006543 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006544 spy->setTouchableRegion(Region{{0, 0, 20, 20}});
6545 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6546
6547 // Inject an event outside the spy window's touchable region.
6548 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6549 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6550 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6551 window->consumeMotionDown();
6552 spy->assertNoEvents();
6553 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6554 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6555 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6556 window->consumeMotionUp();
6557 spy->assertNoEvents();
6558
6559 // Inject an event inside the spy window's touchable region.
6560 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6561 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6562 {5, 10}))
6563 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6564 window->consumeMotionDown();
6565 spy->consumeMotionDown();
6566}
6567
6568/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006569 * A spy window can listen for touches outside its touchable region using the WATCH_OUTSIDE_TOUCHES
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006570 * flag, but it will get zero-ed out coordinates if the foreground has a different owner.
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006571 */
6572TEST_F(InputDispatcherSpyWindowTest, WatchOutsideTouches) {
6573 auto window = createForeground();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006574 window->setOwnerInfo(12, 34);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006575 auto spy = createSpy();
6576 spy->setWatchOutsideTouch(true);
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006577 spy->setOwnerInfo(56, 78);
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006578 spy->setFrame(Rect{0, 0, 20, 20});
6579 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6580
6581 // Inject an event outside the spy window's frame and touchable region.
6582 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006583 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6584 {100, 200}))
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006585 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6586 window->consumeMotionDown();
Prabir Pradhandfabf8a2022-01-21 08:19:30 -08006587 spy->consumeMotionOutsideWithZeroedCoords();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006588}
6589
6590/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006591 * A spy window can pilfer pointers. When this happens, touch gestures that are currently sent to
6592 * any other windows - including other spy windows - will also be cancelled.
6593 */
6594TEST_F(InputDispatcherSpyWindowTest, PilferPointers) {
6595 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006596 auto spy1 = createSpy();
6597 auto spy2 = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006598 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy1, spy2, window}}});
6599
6600 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6601 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6602 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6603 window->consumeMotionDown();
6604 spy1->consumeMotionDown();
6605 spy2->consumeMotionDown();
6606
6607 // Pilfer pointers from the second spy window.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006608 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy2->getToken()));
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006609 spy2->assertNoEvents();
6610 spy1->consumeMotionCancel();
6611 window->consumeMotionCancel();
6612
6613 // The rest of the gesture should only be sent to the second spy window.
6614 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6615 injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
6616 ADISPLAY_ID_DEFAULT))
6617 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6618 spy2->consumeMotionMove();
6619 spy1->assertNoEvents();
6620 window->assertNoEvents();
6621}
6622
6623/**
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006624 * A spy window can pilfer pointers for a gesture even after the foreground window has been removed
6625 * in the middle of the gesture.
6626 */
6627TEST_F(InputDispatcherSpyWindowTest, CanPilferAfterWindowIsRemovedMidStream) {
6628 auto window = createForeground();
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006629 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006630 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6631
6632 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6633 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6634 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6635 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6636 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6637
6638 window->releaseChannel();
6639
6640 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
6641
6642 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6643 injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
6644 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6645 spy->consumeMotionUp(ADISPLAY_ID_DEFAULT);
6646}
6647
6648/**
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006649 * After a spy window pilfers pointers, new pointers that go down in its bounds should be sent to
6650 * the spy, but not to any other windows.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006651 */
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006652TEST_F(InputDispatcherSpyWindowTest, ContinuesToReceiveGestureAfterPilfer) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006653 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006654 auto window = createForeground();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006655
6656 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6657
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006658 // First finger down on the window and the spy.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006659 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6660 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6661 {100, 200}))
6662 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006663 spy->consumeMotionDown();
6664 window->consumeMotionDown();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006665
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006666 // Spy window pilfers the pointers.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006667 EXPECT_EQ(OK, mDispatcher->pilferPointers(spy->getToken()));
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006668 window->consumeMotionCancel();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006669
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006670 // Second finger down on the window and spy, but the window should not receive the pointer down.
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006671 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006672 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006673 .displayId(ADISPLAY_ID_DEFAULT)
6674 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6675 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6676 .x(100)
6677 .y(200))
6678 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6679 .build();
6680 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6681 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6682 InputEventInjectionSync::WAIT_FOR_RESULT))
6683 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6684
Prabir Pradhane680f9b2022-02-04 04:24:00 -08006685 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6686
6687 // Third finger goes down outside all windows, so injection should fail.
6688 const MotionEvent thirdFingerDownEvent =
6689 MotionEventBuilder(AMOTION_EVENT_ACTION_POINTER_DOWN |
6690 (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT),
6691 AINPUT_SOURCE_TOUCHSCREEN)
6692 .displayId(ADISPLAY_ID_DEFAULT)
6693 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6694 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6695 .x(100)
6696 .y(200))
6697 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6698 .pointer(PointerBuilder(/* id */ 2, AMOTION_EVENT_TOOL_TYPE_FINGER).x(-5).y(-5))
6699 .build();
6700 ASSERT_EQ(InputEventInjectionResult::FAILED,
6701 injectMotionEvent(mDispatcher, thirdFingerDownEvent, INJECT_EVENT_TIMEOUT,
6702 InputEventInjectionSync::WAIT_FOR_RESULT))
6703 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6704
6705 spy->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006706 window->assertNoEvents();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006707}
6708
6709/**
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006710 * Even when a spy window spans over multiple foreground windows, the spy should receive all
6711 * pointers that are down within its bounds.
6712 */
6713TEST_F(InputDispatcherSpyWindowTest, ReceivesMultiplePointers) {
6714 auto windowLeft = createForeground();
6715 windowLeft->setFrame({0, 0, 100, 200});
6716 auto windowRight = createForeground();
6717 windowRight->setFrame({100, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006718 auto spy = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006719 spy->setFrame({0, 0, 200, 200});
6720 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, windowLeft, windowRight}}});
6721
6722 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6723 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6724 {50, 50}))
6725 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6726 windowLeft->consumeMotionDown();
6727 spy->consumeMotionDown();
6728
6729 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006730 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006731 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6732 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6733 .pointer(
6734 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6735 .build();
6736 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6737 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6738 InputEventInjectionSync::WAIT_FOR_RESULT))
6739 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6740 windowRight->consumeMotionDown();
6741 spy->consumeMotionPointerDown(1 /*pointerIndex*/);
6742}
6743
6744/**
6745 * When the first pointer lands outside the spy window and the second pointer lands inside it, the
6746 * the spy should receive the second pointer with ACTION_DOWN.
6747 */
6748TEST_F(InputDispatcherSpyWindowTest, ReceivesSecondPointerAsDown) {
6749 auto window = createForeground();
6750 window->setFrame({0, 0, 200, 200});
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006751 auto spyRight = createSpy();
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006752 spyRight->setFrame({100, 0, 200, 200});
6753 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spyRight, window}}});
6754
6755 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6756 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6757 {50, 50}))
6758 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6759 window->consumeMotionDown();
6760 spyRight->assertNoEvents();
6761
6762 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006763 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan07e05b62021-11-19 03:57:24 -08006764 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6765 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6766 .pointer(
6767 PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(150).y(50))
6768 .build();
6769 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6770 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6771 InputEventInjectionSync::WAIT_FOR_RESULT))
6772 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6773 window->consumeMotionPointerDown(1 /*pointerIndex*/);
6774 spyRight->consumeMotionDown();
6775}
6776
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006777/**
6778 * The spy window should not be able to affect whether or not touches are split. Only the foreground
6779 * windows should be allowed to control split touch.
6780 */
6781TEST_F(InputDispatcherSpyWindowTest, SplitIfNoForegroundWindowTouched) {
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006782 // This spy window prevents touch splitting. However, we still expect to split touches
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006783 // because a foreground window has not disabled splitting.
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006784 auto spy = createSpy();
Prabir Pradhan76bdecb2022-01-31 11:14:15 -08006785 spy->setPreventSplitting(true);
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006786
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006787 auto window = createForeground();
6788 window->setFrame(Rect(0, 0, 100, 100));
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006789
6790 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6791
6792 // First finger down, no window touched.
6793 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6794 injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
6795 {100, 200}))
6796 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6797 spy->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6798 window->assertNoEvents();
6799
6800 // Second finger down on window, the window should receive touch down.
6801 const MotionEvent secondFingerDownEvent =
Siarhei Vishniakoua16e3a22022-03-02 15:26:40 -08006802 MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006803 .displayId(ADISPLAY_ID_DEFAULT)
6804 .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
6805 .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
6806 .x(100)
6807 .y(200))
6808 .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
6809 .build();
6810 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
6811 injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
6812 InputEventInjectionSync::WAIT_FOR_RESULT))
6813 << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
6814
6815 window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
6816 spy->consumeMotionPointerDown(1 /* pointerIndex */);
6817}
6818
6819/**
6820 * A spy window will usually be implemented as an un-focusable window. Verify that these windows
6821 * do not receive key events.
6822 */
6823TEST_F(InputDispatcherSpyWindowTest, UnfocusableSpyDoesNotReceiveKeyEvents) {
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006824 auto spy = createSpy();
Prabir Pradhan1376fcd2022-01-21 09:56:35 -08006825 spy->setFocusable(false);
6826
6827 auto window = createForeground();
6828 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {spy, window}}});
6829 setFocusedWindow(window);
6830 window->consumeFocusEvent(true);
6831
6832 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyDown(mDispatcher))
6833 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6834 window->consumeKeyDown(ADISPLAY_ID_NONE);
6835
6836 ASSERT_EQ(InputEventInjectionResult::SUCCEEDED, injectKeyUp(mDispatcher))
6837 << "Inject key event should return InputEventInjectionResult::SUCCEEDED";
6838 window->consumeKeyUp(ADISPLAY_ID_NONE);
6839
6840 spy->assertNoEvents();
6841}
6842
Prabir Pradhand65552b2021-10-07 11:23:50 -07006843class InputDispatcherStylusInterceptorTest : public InputDispatcherTest {
6844public:
6845 std::pair<sp<FakeWindowHandle>, sp<FakeWindowHandle>> setupStylusOverlayScenario() {
6846 std::shared_ptr<FakeApplicationHandle> overlayApplication =
6847 std::make_shared<FakeApplicationHandle>();
6848 sp<FakeWindowHandle> overlay =
6849 new FakeWindowHandle(overlayApplication, mDispatcher, "Stylus interceptor window",
6850 ADISPLAY_ID_DEFAULT);
6851 overlay->setFocusable(false);
6852 overlay->setOwnerInfo(111, 111);
Prabir Pradhan4d5c52f2022-01-31 08:52:10 -08006853 overlay->setTouchable(false);
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006854 overlay->setInterceptsStylus(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006855 overlay->setTrustedOverlay(true);
6856
6857 std::shared_ptr<FakeApplicationHandle> application =
6858 std::make_shared<FakeApplicationHandle>();
6859 sp<FakeWindowHandle> window =
6860 new FakeWindowHandle(application, mDispatcher, "Application window",
6861 ADISPLAY_ID_DEFAULT);
6862 window->setFocusable(true);
6863 window->setOwnerInfo(222, 222);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006864
6865 mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
6866 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6867 setFocusedWindow(window);
6868 window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
6869 return {std::move(overlay), std::move(window)};
6870 }
6871
6872 void sendFingerEvent(int32_t action) {
6873 NotifyMotionArgs motionArgs =
6874 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6875 ADISPLAY_ID_DEFAULT, {PointF{20, 20}});
6876 mDispatcher->notifyMotion(&motionArgs);
6877 }
6878
6879 void sendStylusEvent(int32_t action) {
6880 NotifyMotionArgs motionArgs =
6881 generateMotionArgs(action, AINPUT_SOURCE_TOUCHSCREEN | AINPUT_SOURCE_STYLUS,
6882 ADISPLAY_ID_DEFAULT, {PointF{30, 40}});
6883 motionArgs.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
6884 mDispatcher->notifyMotion(&motionArgs);
6885 }
6886};
6887
Prabir Pradhana3ab87a2022-01-27 10:00:21 -08006888using InputDispatcherStylusInterceptorDeathTest = InputDispatcherStylusInterceptorTest;
6889
6890TEST_F(InputDispatcherStylusInterceptorDeathTest, UntrustedOverlay_AbortsDispatcher) {
6891 ScopedSilentDeath _silentDeath;
6892
Prabir Pradhand65552b2021-10-07 11:23:50 -07006893 auto [overlay, window] = setupStylusOverlayScenario();
6894 overlay->setTrustedOverlay(false);
6895 // Configuring an untrusted overlay as a stylus interceptor should cause Dispatcher to abort.
6896 ASSERT_DEATH(mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}}),
6897 ".* not a trusted overlay");
6898}
6899
6900TEST_F(InputDispatcherStylusInterceptorTest, ConsmesOnlyStylusEvents) {
6901 auto [overlay, window] = setupStylusOverlayScenario();
6902 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6903
6904 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6905 overlay->consumeMotionDown();
6906 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6907 overlay->consumeMotionUp();
6908
6909 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6910 window->consumeMotionDown();
6911 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6912 window->consumeMotionUp();
6913
6914 overlay->assertNoEvents();
6915 window->assertNoEvents();
6916}
6917
6918TEST_F(InputDispatcherStylusInterceptorTest, SpyWindowStylusInterceptor) {
6919 auto [overlay, window] = setupStylusOverlayScenario();
Prabir Pradhan51e7db02022-02-07 06:02:57 -08006920 overlay->setSpy(true);
Prabir Pradhand65552b2021-10-07 11:23:50 -07006921 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6922
6923 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6924 overlay->consumeMotionDown();
6925 window->consumeMotionDown();
6926 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6927 overlay->consumeMotionUp();
6928 window->consumeMotionUp();
6929
6930 sendFingerEvent(AMOTION_EVENT_ACTION_DOWN);
6931 window->consumeMotionDown();
6932 sendFingerEvent(AMOTION_EVENT_ACTION_UP);
6933 window->consumeMotionUp();
6934
6935 overlay->assertNoEvents();
6936 window->assertNoEvents();
6937}
6938
Prabir Pradhan6dfbf262022-03-14 15:24:30 +00006939/**
6940 * Set up a scenario to test the behavior used by the stylus handwriting detection feature.
6941 * The scenario is as follows:
6942 * - The stylus interceptor overlay is configured as a spy window.
6943 * - The stylus interceptor spy receives the start of a new stylus gesture.
6944 * - It pilfers pointers and then configures itself to no longer be a spy.
6945 * - The stylus interceptor continues to receive the rest of the gesture.
6946 */
6947TEST_F(InputDispatcherStylusInterceptorTest, StylusHandwritingScenario) {
6948 auto [overlay, window] = setupStylusOverlayScenario();
6949 overlay->setSpy(true);
6950 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6951
6952 sendStylusEvent(AMOTION_EVENT_ACTION_DOWN);
6953 overlay->consumeMotionDown();
6954 window->consumeMotionDown();
6955
6956 // The interceptor pilfers the pointers.
6957 EXPECT_EQ(OK, mDispatcher->pilferPointers(overlay->getToken()));
6958 window->consumeMotionCancel();
6959
6960 // The interceptor configures itself so that it is no longer a spy.
6961 overlay->setSpy(false);
6962 mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {overlay, window}}});
6963
6964 // It continues to receive the rest of the stylus gesture.
6965 sendStylusEvent(AMOTION_EVENT_ACTION_MOVE);
6966 overlay->consumeMotionMove();
6967 sendStylusEvent(AMOTION_EVENT_ACTION_UP);
6968 overlay->consumeMotionUp();
6969
6970 window->assertNoEvents();
6971}
6972
Garfield Tane84e6f92019-08-29 17:28:41 -07006973} // namespace android::inputdispatcher